JavaScript Array every()
Příklad 1
Zkontrolujte, zda jsou všechny hodnoty ve věkových skupinách[] starší 18 let:
const ages = [32, 33, 16, 40];
ages.every(checkAge)
function checkAge(age) {
return age > 18;
}
Další příklady „Vyzkoušejte si to sami“ níže.
Definice a použití
Metoda every()
vykonává funkci pro každý prvek pole.
Metoda every()
se vrátí true
, pokud funkce vrátí hodnotu true pro všechny prvky.
Metoda every()
se vrátí false
, pokud funkce vrátí hodnotu false pro jeden prvek.
Metoda every()
neprovádí funkci pro prázdné prvky.
Metoda every()
nemění původní pole
Syntax
array.every(function(currentValue, index, arr), thisValue)
Parametry
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. |
Návratová hodnota
Typ | Popis |
Booleovský |
true pokud všechny prvky projdou testem, jinak false . |
Podpora prohlížeče
every()
je funkce ECMAScript5 (ES5).
ES5 (JavaScript 2009) plně podporován ve všech prohlížečích:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
Další příklady
Zkontrolujte, zda jsou všechny odpovědi stejné:
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);
}
}
Zkontrolujte, zda všechny hodnoty přesahují určité číslo:
<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>