Does reduce in JavaScript/ECMAScript 5 stop on first false when using with and operator?

StackOverflow https://stackoverflow.com/questions/20641409

  •  18-09-2022
  •  | 
  •  

Pregunta

var a = [7,8,9,4,5,3,2,0,44];
[0,2,8].reduce(function(p,c,i,arr){return p && (a.indexOf(c)>-1) },true)
//true

[0,2,8,45].reduce(function(p,c,i,arr){return p && (a.indexOf(c)>-1) },true)
//false

[0,2,8,44].reduce(function(p,c,i,arr){return p && (a.indexOf(c)>-1) },true)
//true

Works fine!

Is it smart enough to stop when callback fn returns false the first time ?

BTW that code checks if array 'a' contains everything array 'arr' contains .

¿Fue útil?

Solución

Is it smart enough to stop when callback fn returns false the first time ?

No. The return value of the callback just becomes the value of its first parameter in the next iteration.

For example, in this call:

[0,2,8,45].reduce(function(p,c,i,arr){return p && (a.indexOf(c)>-1) },true)

In each iteration, these are the values of p, c, and i (arr is always [0,2,8,45]):

p     c  i  return
true  0  0  true
true  2  1  true
true  8  2  true
true 45  3  false

The last return value is the final return value of reduce. It will always iterate over all values in the array.

~~~~~~~~~~~~~~~~~~~~~~~~~~

If you want something that stops on the first false, use every:

[0,45,2].every(function(c,i){return a.indexOf(c)>-1 }) // false. Stops on 45

Otros consejos

No.
The reduce() function doesn't know what your callback does; it has no idea it's always short-circuiting.

Call every() instead.

No, the reduce function invokes its callback for each value in the array. From the documentation on the reduce method:

reduce executes the callback function once for each element present in the array, excluding holes in the array, receiving four arguments: the initial value (or value from the previous callback call), the value of the current element, the current index, and the array over which iteration is occurring.

Your piece of code "seems to work" because && operator evaluates to true only when both its parameters are truthy. When you meet first false value, the accumulator value in reduce function (the first argument) becomes false, and after that there is no way to make it true again: false && <any value> is always false.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top