Please, can someone explain me behavior of function every.
I have an array and I want to apply function every to it. Function every is taking a predicate.
My simple predicate:
function test() {
return function(arg) {
console.log(arg);
return true;
}
}
I called function every on the array with my predicate:
const predicate = test();
[1, 2, 3].every(predicate);
Result:
Output:
1
2
3
BUT when I changed my predicate to this:
function test() {
return function(...args) {
console.log(...args);
return true;
}
}
The result is so weird for me:
Output:
1 0 [ 1, 2, 3 ]
2 1 [ 1, 2, 3 ]
3 2 [ 1, 2, 3 ]
Why so? I expection somethin like this:
[1]
[2]
[3]
function test() {
return function(arg) {
console.log(arg);
return true;
}
}
function test2() {
return function(...args) {
console.log(...args);
return true;
}
}
const predicate = test();
const predicate2 = test2();
[1, 2, 3].every(predicate);
[1, 2, 3].every(predicate2);
CodePudding user response:
...arg
is like a passing of all the arguments that .every
method accepts.
i.e. An array element
, index of the element
and a whole array
.
Hence, to print values as an array. You can simply return the values in a square bracket.
Demo :
[1, 2, 3].every(function(arg) {
console.log([arg]);
return true;
});
CodePudding user response:
every(), like map() and forEach(), calls function with two arguments: value and index.