2.6 KiB
2.6 KiB
id, title, localeTitle, challengeType
id | title | localeTitle | challengeType |
---|---|---|---|
5675e877dbd60be8ad28edc6 | Iterate Through an Array with a For Loop | Iterar a través de una matriz con un bucle For | 1 |
Description
for
. Este código dará salida a cada elemento de la matriz arr
a la consola:
var arr = [10,9,8,7,6];Recuerde que las matrices tienen numeración basada en cero, lo que significa que el último índice de la matriz es la longitud - 1. Nuestra condición para este bucle es
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
i < arr.length
, que se detiene cuando i
tiene la longitud - 1.
Instructions
total
a 0
. Use un bucle for
para agregar el valor de cada elemento de la matriz myArr
al total
.
Tests
tests:
- text: <code>total</code> debe ser declarado e inicializado a 0
testString: 'assert(code.match(/var.*?total\s*=\s*0.*?;/), "<code>total</code> should be declared and initialized to 0");'
- text: <code>total</code> debe ser igual a 20
testString: 'assert(total === 20, "<code>total</code> should equal 20");'
- text: Debe usar un bucle <code>for</code> para iterar a través de <code>myArr</code>
testString: 'assert(code.match(/for\s*\(/g).length > 1 && code.match(/myArr\s*\[/), "You should use a <code>for</code> loop to iterate through <code>myArr</code>");'
- text: No establezca el <code>total</code> a 20 directamente
testString: 'assert(!code.match(/total[\s\+\-]*=\s*(\d(?!\s*[;,])|[1-9])/g), "Do not set <code>total</code> to 20 directly");'
Challenge Seed
// Example
var ourArr = [ 9, 10, 11, 12];
var ourTotal = 0;
for (var i = 0; i < ourArr.length; i++) {
ourTotal += ourArr[i];
}
// Setup
var myArr = [ 2, 3, 4, 5, 6];
// Only change code below this line
After Test
console.info('after the test');
Solution
var ourArr = [ 9, 10, 11, 12];
var ourTotal = 0;
for (var i = 0; i < ourArr.length; i++) {
ourTotal += ourArr[i];
}
var myArr = [ 2, 3, 4, 5, 6];
var total = 0;
for (var i = 0; i < myArr.length; i++) {
total += myArr[i];
}