Check if all values in ages[] are over 18:
const ages = [32, 33, 16, 40];
ages.every(checkAge)
function checkAge(age) {
return age > 18;
}
Try it Yourself »
More examples below.
The every()
method executes a function for each array element.
The every()
method returns true
if the function returns true for all elements.
The every()
method returns false
if the function returns false for one element.
The every()
method does not execute the function for empty elements.
The every()
method does not change the original array
array.every(
function(currentValue, index, arr), thisValue)
Parameter | Description |
function() | Required. A function to be run for each element in the array. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default undefined .A value passed to the function as its this value. |
Type | Description |
Boolean | true if all elements pass the test, otherwise false . |
Check if all answers are the same:
const survey = [
{ name: "Steve", answer: "Yes"},
{ name: "Jessica", answer: "Yes"},
{ name: "Peter", answer: "Yes"},
{ name: "Elaine", answer: "No"}
];
let result = survey.every(isSameAnswer);
function isSameAnswer(el, index, arr) {
if (index === 0) {
return true;
} else {
return (el.answer === arr[index - 1].answer);
}
}
Try it Yourself »
Check if all values are over a specific number:
<p><input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const ages = [32, 33, 12, 40];
function checkAge(age) {
return age > document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.every(checkAge);
}
</script>
Try it Yourself »
every()
is an ECMAScript5 (ES5) feature.
ES5 (JavaScript 2009) fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!