Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Array.prototype.every()

El mètode every() comprova si tots els elements d'un array passen el test implementat per la funció proporcionada.

Sintaxi

arr.every(callback[, thisArg])

Paràmetres

callback
Funció utilitzada com a test per a cada element, rep tres arguments:
valorActual
L'element de l'array que està sent avaluat.
posició
La posició que l'element passat al primer paràmetre ocupa dins l'array.
array
L'array des del que s'ha cridat el mètode every().
thisArg
Opcional. Valor que valdrà la variable this quan s'estigui executant la funció callback.

Descripció

every() executa la funció callback un cop per a cada element present a l'array fins que troba un per al qual callback retorna un valor falsy (és a dir, un valor que esdebé fals si es realitza una conversió de tipus a Boolean). Si es troba aquest element, el mètode every retorna immediatament false. En cas contrari, si callback ha retornat un valor true per a tots els elements, every retornarà true. Només s'invocarà la funció callback en les posicions de l'array que tinguin un valor assignat, és a dir, mai es cridarà per a posicions que han estat esborrades o el valor de les quals no ha estat mai assignat.

S'invoca callback amb tres arguments: el valor de l'element, la posició de l'element dins l'array, i l'objecte array que es recorrerà.

Si es proporciona el paràmetre thisArg al mètode every(), aquest es passarà a callback quan s'invoqui, i serà el valor que mostrarà la variable this. En cas contrari, s'utilitzarà el valor undefined com a valor per a this. El valor de this observable en última instància per callback es determinarà d'acord a les regles per a determinar el valor de this observat per una funció.

every() no mutarà l'array quan sigui cridada.

El rang d'elements processat per every() és determinat abans de la primera invocació de callback. Els elements que s'afegeixin a l'array després de la crida a every() no seran visitats per callback. Si el valor d'un element encara no visitat canvia, el valor que es passarà a callback serà el valor que tingui aquest element a l'hora de visitar-lo; els elements que s'esborrin no es visitaran.

every es comporta com un quantificador "for all" en matemàtiques. En concret, per a un array buit retornarà true (s'anomena veritat per buit el fet que tots els elements d'un grup buit satisfacin qualsevol condició donada).

Exemples

Comprovar el tamany de tots els elements d'un array

L'exemple següent comprova si tots els elements d'un array son majors de 10.

function isBigEnough(element, index, array) {
  return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough);   // false
[12, 54, 18, 130, 44].every(isBigEnough); // true

Utilitzar funcions flexta

Les funcions fletxa ofereixen una sintaxi reduïda per a realitzar el mateix test.

[12, 5, 8, 130, 44].every(elem => elem >= 10); // false
[12, 54, 18, 130, 44].every(elem => elem >= 10); // true

Polyfill

every va ser afegida  al standard ECMA-262 en la cinquena edició; és per això que pot no estar disponible en certes implementacions del standard. Es pot proporcionar la seva funcionalitat inserint l'script següent a l'inici dels vostres scripts, permetent l'ús de every() en implementacions que no la suporten de forma nativa. Aquest algoritme és exactament l'especificat a l'ECMA-262, cinquena edició, assumint que Object i TypeError tenen els valors originals i que callbackfn.call es correspon amb el valor original de Function.prototype.call.

if (!Array.prototype.every) {
  Array.prototype.every = function(callbackfn, thisArg) {
    'use strict';
    var T, k;

    if (this == null) {
      throw new TypeError('this is null or not defined');
    }

    // 1. Let O be the result of calling ToObject passing the this 
    //    value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get internal method
    //    of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If IsCallable(callbackfn) is false, throw a TypeError exception.
    if (typeof callbackfn !== 'function') {
      throw new TypeError();
    }

    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
    if (arguments.length > 1) {
      T = thisArg;
    }

    // 6. Let k be 0.
    k = 0;

    // 7. Repeat, while k < len
    while (k < len) {

      var kValue;

      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the HasProperty internal 
      //    method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      if (k in O) {

        // i. Let kValue be the result of calling the Get internal method
        //    of O with argument Pk.
        kValue = O[k];

        // ii. Let testResult be the result of calling the Call internal method
        //     of callbackfn with T as the this value and argument list 
        //     containing kValue, k, and O.
        var testResult = callbackfn.call(T, kValue, k, O);

        // iii. If ToBoolean(testResult) is false, return false.
        if (!testResult) {
          return false;
        }
      }
      k++;
    }
    return true;
  };
}

Especificacions

Especificaicó Estat Comentaris
ECMAScript 5.1 (ECMA-262)
The definition of 'Array.prototype.every' in that specification.
Standard Definició inicial. Implemnetat a JavaScript 1.6.
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Array.prototype.every' in that specification.
Standard  
ECMAScript 2016 Draft (7th Edition, ECMA-262)
The definition of 'Array.prototype.every' in that specification.
Draft  

Compatibilitat amb navegadors

Característica Chrome Firefox (Gecko) Internet Explorer Opera Safari
Suport bàsic (Yes) 1.5 (1.8) 9 (Yes) (Yes)
Característica Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Suport bàsic (Yes) (Yes) 1.0 (1.8) (Yes) (Yes) (Yes)

Vegeu també

Document Tags and Contributors

 Contributors to this page: enTropy
 Last updated by: enTropy,