问题
function each(collection, callback) {
var arr = [];
for(var i = 0; i < collection.length; i++) {
var result = callback(collection[i])
if (typeof result !== 'undefined') {
arr.push(callback(collection[i]));
}
}
return arr
}
function isNumber(item) {
if (typeof item === "number") {
return item * 2;
}
}
I am trying to understand higher order functions. The above works, but is apparently not best practice to return a value with isNumber
. I have been told that a Boolean value should be returned. Why? It works.
Update: It appears to be because of the function name! Thanks everyone I just thought there might be some technical reason
回答1:
If a function is called isNumber
, it should return a boolean.
Also, your each function is a map
not an each
. In that case your code should probably look like.
function flatMap(collection, callback) {
var arr = [];
for(var i = 0; i < collection.length; i++) {
var result = callback(collection[i])
if (typeof result !== 'undefined') {
arr.push(callback(collection[i]));
}
}
return arr;
}
function times2(item) {
if (typeof item === "number") {
return item * 2;
}
return item;
}
map([1,2,3,"hello"], times2);
If you wanted iteration that can be stopped, then it would look like
function iterate(collection, callback) {
for(var i = 0; i < collection.length; i++) {
var result = callback(collection[i])
if (typeof result === false) {
return;
}
}
}
function doSomethingAndStopIfNotANumber(item) {
console.log(item);
return typeof item == "number";
}
iterate([1,2,3, "hello", 4, 5], doSomethingAndStopIfNotANumber);
Note that Array.prototype.forEach does not allow you to stop iteration by returning false, for that you'd need to misuse Array.prototype.every (because that function returns a boolean, so it's just a semantic problem, not like map where you build an array and throw it away) or write a function like I did above.
来源:https://stackoverflow.com/questions/37861822/higher-order-functions-returning-anything-but-a-non-boolean-is-questionable-why