Instagram | Twitter | LinkedIn
What is the output of the following code ?
A. 28
B. [4, 6, 10, 14, 22]
C. true
馃憖 Click here to see the correct answer and explanation
| Correct Answer | Explanation |
|---|---|
| A | The reduce() method executes a reducer function (callback) once for each assigned value present in the array, resulting in single output value. The reducer function takes four arguments: accumulator (acc), current Value (cur), current Index (idx), source Array (src). In this case, we are doing the following: First call: accumulator: 2 (first value of the array), currentValue: 3 (second value of the array), return value: 5 (sum of 2 + 3); Second call: accumulator: 5 (last return value), currentValue: 5 (third value of the array), return value: 10 (sum of 5 + 5); Third call: accumulator: 10 (last return value), currentValue: 7 (fourth value of the array), return value: 17 (sum of 10 + 7); Fourth call: accumulator: 17 (last return value), currentValue: 11 (fifth value of the array), return value: 28 (sum of 17 + 11). |
Explanation based on 馃憠馃徏 Array.prototype.reduce()
驴 Qu茅 imprime el siguiente c贸digo ?
A. 28
B. [4, 6, 10, 14, 22]
C. true
馃憖 Haz click aqu铆 para ver la respuesta correcta y su explicaci贸n
| Respuesta correcta | Explicaci贸n |
|---|---|
| A | El m茅todo reduce() ejecuta una funci贸n reductora (callback) una vez por cada elemento presente en el array, devolviendo como resultado un 煤nico valor. La funci贸n reductora recibe cuatro argumentos: acumulador (acc), valor Actual (cur), 铆ndice actual (idx) y array (src). En este caso, estamos haciendo lo siguiente: Primera llamada: acumulador: 2 (primer valor del array), valor actual: 3 (segundo valor del array), valor devuelto: 5 (suma de 2 + 3); Segunda llamada: acumulador: 5 (煤ltimo valor devuelto), valor actual: 5 (tercer valor del array), valor devuelto: 10 (suma de 5 + 5); Tercera llamada: acumulador: 10 (煤ltimo valor devuelto), valor actual: 7 (cuarto valor del array), valor devuelto: 17 (suma de 10 + 7); Cuarta llamada: acumulador: 17 (煤ltimo valor devuelto), valor actual: 11 (quinto valor del array), valor devuelto: 28 (suma de 17 + 11). |
Explicaci贸n basada en 馃憠馃徏 Array.prototype.reduce()

