JavaScript Array every() method
JavaScript Array every() method
Instance
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网</title> </head> <body> <p>点击按钮检测数组的所有元素是否都大于 18 :</p> <button onclick="myFunction()">点我</button> <p id="demo"></p> <script> var ages = [32, 33, 16, 40]; function checkAdult(age) { return age >= 18; } function myFunction() { document.getElementById("demo").innerHTML = ages.every(checkAdult); } </script> </body> </html>
Run instance»
Click "Run" Example" button to view online examples
Definition and usage
every() method is used to detect whether all elements of the array meet the specified conditions (provided through the function).
every() method uses the specified function to detect all elements in the array:
- If it is detected that one element in the array is not satisfied, the entire expression returns false , and the remaining elements will not be tested again.
- Returns true if all elements meet the condition.
Note: every() will not detect empty arrays.
Note: every() will not change the original array.
Browser support
The number in the table indicates the version number of the first browser that supports this method.
Syntax
array.every(function(currentValue,index,arr), thisValue)
Parameter description
Parameter | Description |
---|---|
function(currentValue, index,arr) | Required. Function, each element in the array will execute this function Function parameters: Parameter description currentValue must be. The value index of the current element is optional. The index value arr of the current element is optional. The array object to which the current element belongs |
thisValue | is optional. The object is used as the execution callback, passed to the function, and used as the value of "this". If thisValue is omitted, the value of "this" is "undefined" |
##Technical details
Boolean value. Returns true if all elements pass the test, false otherwise. | |
---|---|
1.6 |
Instance
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网</title>
</head>
<body>
<p>点击按钮检测数组的所有元素是否都大于输入框中指定的数字。</p>
<p>最小年龄: <input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">点我</button>
<p>是否所有年龄都符号条件? <span id="demo"></span></p>
<script>
var ages = [32, 33, 12, 40];
function checkAdult(age) {
return age >= document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.every(checkAdult);
}
</script>
</body>
</html>
Run Instance»Click the "Run Instance" button to view the online instance