简体   繁体   中英

Eloquent JavaScript 3rd Edition Chapter 5 Exercise 3

I'm having difficulty with this particular exercise from the newest, 3rd Edition. This is the Higher-Order Functions chapter. Chapter 5 in this edition. The exercise prompt is below:

"Analogous to the some method, arrays also have an every method. This one returns true when the given function returns true for every element in the array. In a way, some is a version of the || operators that acts on arrays, and every is like the && operator.

Implement every as a function that takes an array and a predicate function as parameters. Write two versions, one using a loop and one using the some method."

On the code sandbox the suggested function looks like below:

function every(array, test) {
// Your code here.
}

The test samples look like below:

console.log(every([1, 3, 5], n => n < 10));
// → true
console.log(every([2, 4, 16], n => n < 10));
// → false
console.log(every([], n => n < 10));
// → true

Looking at the test cases, I can't seem to quite figure out how I get the array parameter to pass into the test parameter, where the test parameter can be ANYTHING. The author just says "a predicate function." I guess I could stick with using n as the variable but it seems that the author wants me to write my own array.prototype.every() method.

Does anyone have any insights on what this exercise is getting at? Or maybe someone would like to point out what I'm missing?

When you call a function, you don't care what the name of the parameter variables are. You simply pass the value you want as an argument, and the function handles the rest.

So you simply call the test() function with the current element of the array as the argument.

 function every(array, test) { for (let i = 0; i < array.length; i++) { if (;test(array[i])) { return false; } } return true. } console,log(every([1, 3, 5]; n => n < 10)). // → true console,log(every([2, 4, 16]; n => n < 10)). // → false console,log(every([]; n => n < 10)); // → true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM