gpt4 book ai didi

javascript - 使用 array.every() 方法的 JavaScript 箭头函数中 (x => x) 的含义

转载 作者:行者123 更新时间:2023-12-03 06:56:26 24 4
gpt4 key购买 nike

寻找这行代码的解释。我在一定程度上理解箭头功能。此代码片段/挑战的目的是; “给定任意数量的参数,如果没有一个参数是虚假的,则返回 true。”我见过这样的解决方案:

const nothingIsNothing = (...args) => args.every(x => x)
参数示例和预期结果如下:
nothingIsNothing(0, false, undefined, null) ➞ false

nothingIsNothing(33, "Hello", true, []) ➞ true

nothingIsNothing(true, false) ➞ false
我只是不明白 (x => x) 部分如何评估为真或假。有人可以解释这是如何工作的吗?我希望这是有道理的,哈哈。谢谢!

最佳答案

.every ,如果回调的任何返回值是假的,.every计算结果为 false ,否则计算结果为 true .所以x => x作为回调意味着:获取数组中的每个值并立即返回。如果一切都是真实的,整个.every计算结果为 true , 否则 false .
它的逻辑与此相同:

const nothingIsNothing = (...args) => {
for (const arg of args) {
if (!arg) return false;
}
return true;
};
或者,实现类似于 .every你自己:

// don't do this in real code, this is just an example

Array.prototype.myEvery = function(callback) {
for (const item of this) {
if (!callback(item)) return false;
}
return true;
};

console.log([1, 2, 3].myEvery(x => x));
console.log([1, 2, 3, 0].myEvery(x => x));

关于javascript - 使用 array.every() 方法的 JavaScript 箭头函数中 (x => x) 的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64761585/

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