Reputation: 557
New to js and I'm attempting to solve a really simple problem. I'm not sure why it's not working though. Must be a js quirk I am unfamiliar with. Can someone tell me why x would return back as undefined thus causing my function to return false when it should return true? I'm trying to replicate the 'every' method for arrays and return false if one of the array elements returns false from my callback.
I've attempted to debug with webstorm and I still could not find the solution. Here is my code,
function every_loop(array, test) {
for (let index = 0; array.length - 1; index++) {
let x = test(array[index]);
if (!x) {
console.log(array[index], index);
return false;
}
}
return true;
}
console.log(every_loop([1, 2, 3, 4, 5], n => n >= 1));
My output is false when it should be true. Also, right before it outputs false, it shows undefined as a value for array[index] which leads me to believe that my for loop parameters are incorrect but that isn't the case either. Any help would be appreciated. Thanks
Upvotes: 0
Views: 60
Reputation: 2049
replace
for (let index = 0; array.length - 1; index++) {
with
for (let index = 0; index < array.length; index++) {
Upvotes: 1
Reputation: 18639
Your condition in for
loop will be always true. (array.length-1==4
). So use this instead:
function every_loop(array, test) {
for (let index = 0; index<array.length;index++) {
let x = test(array[index]);
if (!x) {
return false;
}
}
return true;
}
console.log(every_loop([1,2,3,4,5], n => n >= 1));
console.log(every_loop([0,1,2,3,4,5], n => n >= 1));
Upvotes: 1
Reputation: 135415
Your for
loop is broken. I would recommend for..of
-
function everyLoop (arr, test) {
for (const x of arr)
if (!test(x))
return false
return true
}
console.log(everyLoop([1,2,3,4,5], n => n >= 1)) // true
console.log(everyLoop([1,2,3,4,5], n => n >= 2)) // false
You said it's practice, but just know JavaScript does include a built-in Array#every
that does exactly this -
console.log([1,2,3,4,5].every(n => n >= 1)) // true
console.log([1,2,3,4,5].every(n => n >= 2)) // false
Upvotes: 1
Reputation: 3731
you are missing the clause of the second parameter of the for
loop.
changing it to index <= array.length - 1
fixes your code.
function every_loop(array, test) {
for (let index = 0; index <= array.length - 1; index++) {
let x = test(array[index]);
if (!x) {
console.log(array[index]);
return false;
}
}
return true;
}
console.log(every_loop([1, 2, 3, 4, 5], n => n >= 1));
Upvotes: 2