diff options
author | Florian Merz <me@fiji-flo.de> | 2021-02-11 14:46:50 +0100 |
---|---|---|
committer | Florian Merz <me@fiji-flo.de> | 2021-02-11 14:46:50 +0100 |
commit | a55b575e8089ee6cab7c5c262a7e6db55d0e34d6 (patch) | |
tree | 5032e6779a402a863654c9d65965073f09ea4182 /files/es/web/javascript/reference/global_objects/array/every/index.html | |
parent | 8260a606c143e6b55a467edf017a56bdcd6cba7e (diff) | |
download | translated-content-a55b575e8089ee6cab7c5c262a7e6db55d0e34d6.tar.gz translated-content-a55b575e8089ee6cab7c5c262a7e6db55d0e34d6.tar.bz2 translated-content-a55b575e8089ee6cab7c5c262a7e6db55d0e34d6.zip |
unslug es: move
Diffstat (limited to 'files/es/web/javascript/reference/global_objects/array/every/index.html')
-rw-r--r-- | files/es/web/javascript/reference/global_objects/array/every/index.html | 195 |
1 files changed, 195 insertions, 0 deletions
diff --git a/files/es/web/javascript/reference/global_objects/array/every/index.html b/files/es/web/javascript/reference/global_objects/array/every/index.html new file mode 100644 index 0000000000..540ebbdfa9 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/array/every/index.html @@ -0,0 +1,195 @@ +--- +title: Array.prototype.every() +slug: Web/JavaScript/Referencia/Objetos_globales/Array/every +tags: + - Arreglo + - ECMAScript 5 + - JavaScript + - Prototipo + - metodo + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/every +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary">Determina si todos los elementos en el array satisfacen una condición.</span></p> + +<div class="note"> +<p><strong>Precaución</strong>: ¡Llamar este método en un array vacío devuelve <code>true</code> para cualquier condición!</p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/array-every.html")}}</div> + +<p class="hidden">La fuente de este ejemplo interactivo se encuentra en GitHub. Si desea contribuir con el proyecto de ejemplos interactivos, clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> y envíenos un<em>pull</em><em> request</em>.</p> + +<h2 id="Sintaxis">Sintaxis</h2> + +<pre class="syntaxbox"><var>arr</var>.every(<var>callback</var>(<var>element</var>[, <var>index</var>[, <var>array</var>]])[, <var>thisArg</var>])</pre> + +<h3 id="Parámetros">Parámetros</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Una función para probar cada elemento; recibe tres argumentos: + <dl> + <dt><code>currentValue</code> (required)</dt> + <dd>El elemento actual del arreglo que está siendo procesado.</dd> + <dt><code>index</code> {{Optional_inline}}</dt> + <dd>El índice del elemento actual del arreglo que está siendo procesado.</dd> + <dt><code>array</code> {{Optional_inline}}</dt> + <dd>El arreglo sobre el cual fue llamado <code>every</code>.</dd> + </dl> + </dd> + <dt><code>thisArg</code> {{Optional_inline}}</dt> + <dd>Valor por usar como <code>this</code> cuando se ejecute <code>callback</code>.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p><code>true</code> si la función de devolución de llamada devuelve un valor de {{Glossary("truthy")}} para cada elemento de matriz; de lo contrario, <code>false</code>.</p> + +<h2 id="Descripción">Descripción</h2> + +<p>El método <code>every</code> ejecuta la función <code>callback</code> dada una vez por cada elemento presente en el arreglo hasta encontrar uno que haga retornar un valor falso a <code>callback</code> (un valor que resulte falso cuando se convierta a booleano). Si no se encuentra tal elemento, el método <code>every</code> de inmediato retorna <code>false</code>. O si <code>callback</code> retorna verdadero para todos los elementos, <code>every</code> retornará <code>true</code>. <code>callback</code> es llamada sólo para índices del arreglo que tengan valores asignados; no se llama para índices que hayan sido eliminados o a los que no se les haya asignado un valor.</p> + +<p><code>callback</code> es llamada con tres argumetos: el valor del elemento, el índice del elemento y el objeto Array que está siendo recorrido.</p> + +<p>Si se proporciona un parámetro <code>thisArg</code> a <code>every</code>, será pasado a la función <code>callback</code> cuando sea llamada, usándolo como valor <code>this</code>. En otro caso, se pasará el valor <code>undefined</code> para que sea usado como valor <code>this</code>. El valor <code>this</code> observable por parte de <code>callback</code> se determina de acuerdo a <a href="/es/docs/Web/JavaScript/Reference/Operators/this">las normas usuales para determinar el <code>this</code> visto por una función</a>.</p> + +<p><code>every</code> no modifica el arreglo sobre el cual es llamado.</p> + +<p>El intervalo de elementos procesados por <code>every</code> se establece antes de la primera llamada a <code>callback</code>. Los elementos que se agreguen al arreglo después de que la función <code>every</code> comience no serán vistos por la función <code>callback</code>. Si se modifican elementos existentes en el arreglo, su valor cuando sea pasado a <code>callback</code> será el valor que tengan cuando sean visitados; los elementos que se eliminen no serán visitados.</p> + +<p><code>every</code> opera como el cuantificador "para todo" en matemáticas. En particular con el arreglo vacío retorna true. (es una <a href="http://en.wikipedia.org/wiki/Vacuous_truth#Vacuous_truths_in_mathematics">verdad vacua</a> que todos los elementos del <a href="http://en.wikipedia.org/wiki/Empty_set#Common_problems">conjunto vacío</a> satisfacen una condición dada.)</p> + +<h2 id="Ejemplos">Ejemplos</h2> + +<h3 id="Probando_el_tamaño_de_todos_los_elementos_de_un_arreglo">Probando el tamaño de todos los elementos de un arreglo</h3> + +<p>El siguiente ejemplo prueba si todos los elementos de un arreglo son mayores que 10.</p> + +<pre class="brush: js">function esSuficientementeGrande(elemento, indice, arrreglo) { + return elemento >= 10; +} +[12, 5, 8, 130, 44].every(esSuficientementeGrande); // false +[12, 54, 18, 130, 44].every(esSuficientementeGrande); // true +</pre> + +<h3 id="Usar_funciones_flecha">Usar funciones flecha</h3> + +<p>Las <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">funciones flecha</a> proveen una sintaxis más corta para la misma prueba.</p> + +<pre class="brush: js">[12, 5, 8, 130, 44].every(elem => elem >= 10); // false +[12, 54, 18, 130, 44].every(elem => elem >= 10); // true</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>every</code> fue añadida a la norma ECMA-262 en la 5ta edición; por lo que podría no estar presente en otras implementaciones de la norma. Puede sobrellevarlo insertando el siguiente código al comienzo de su programa, permitiendo el uso de <code>every</code> en implementación que no lo soporten de manera nativa. Este algoritmo es exactamente el especificado en ECMA-262, 5ta edición, suponiendo que <code>Object</code> y <code>TypeError</code> tienen sus valores originales y que <code>callbackfn.call</code> evalua al valor original de {{jsxref("Function.prototype.call")}}</p> + +<pre class="brush: js">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; + }; +} +</pre> + +<h2 id="Especificaciones">Especificaciones</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificación</th> + <th scope="col">Estado</th> + <th scope="col">Comentario</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.16', 'Array.prototype.every')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.every', 'Array.prototype.every')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.every', 'Array.prototype.every')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidad_con_navegadores">Compatibilidad con navegadores</h2> + +<div> +<p>{{Compat("javascript.builtins.Array.every")}}</p> +</div> + +<div id="compat-mobile"></div> + +<h2 id="Ver_también">Ver también</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("TypedArray.prototype.every()")}}</li> +</ul> |