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 .
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 .
Share Improve this question asked Dec 17, 2013 at 17:58 Amogh TalpallikarAmogh Talpallikar 12.2k15 gold badges84 silver badges135 bronze badges 2-
That's not the purpose of
.reduce
. You might be looking for.every
: developer.mozilla/en-US/docs/Web/JavaScript/Reference/…. – Felix Kling Commented Dec 17, 2013 at 18:00 - Oh! thanks!!! but my reduce was working. lol! – Amogh Talpallikar Commented Dec 17, 2013 at 18:02
3 Answers
Reset to default 4Is it smart enough to stop when callback fn returns false the first time ?
No. The return value of the callback just bees 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
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) bees false
, and after that there is no way to make it true
again: false && <any value>
is always false
.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745170583a4614900.html
评论列表(0条)