gpt4 book ai didi

javascript - 高阶函数返回非 boolean 值以外的任何内容都是有问题的。为什么?

转载 作者:行者123 更新时间:2023-11-27 22:53:18 24 4
gpt4 key购买 nike

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;
}
}

我正在尝试理解高阶函数。上面的方法有效,但显然不是使用 isNumber 返回值的最佳实践。有人告诉我应该返回 boolean 值。为什么?它有效。

更新:看来是因为函数名的原因!谢谢大家,我只是觉得可能有一些技术原因

最佳答案

如果调用函数isNumber,它应该返回一个 boolean 值。

此外,您的 every 函数是一个 map 而不是 each。在这种情况下,您的代码可能应该如下所示。

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);

如果你想要可以停止的迭代,那么它看起来像

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);

请注意Array.prototype.forEach不允许您通过返回 false 来停止迭代,因为您需要滥用 Array.prototype.every (因为该函数返回一个 boolean 值,所以这只是一个语义问题,不像映射那样构建一个数组并将其丢弃)或像我上面那样编写一个函数。

关于javascript - 高阶函数返回非 boolean 值以外的任何内容都是有问题的。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37861822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com