gpt4 book ai didi

javascript - 当一个简单的 For Loop 工作正常时,我的 forEach 方法有什么问题

转载 作者:数据小太阳 更新时间:2023-10-29 05:05:03 26 4
gpt4 key购买 nike

所以,我有一个简单的任务,给定数组:let arr = [true, false, true, false, true];我需要将 true 反转为 false,反之亦然。我已经设法用 for 循环做到了这一点:而且它工作正常。

现在,我正尝试对 forEach 做同样的事情,但我不明白为什么这行不通。所以,这是我的代码:

for (let i = 0; i < arr.length; i++) {
if (arr[i] === true) arr[i] = false;
else arr[i] = true;
} // it works

// for some reason, this doesn't
arr2.forEach(el => el === true ? el = false : el = true);
console.log(arr)

//Neither this:
arr.forEach(el => el === true && el = false || el === false && el = true);
console.log(arr)

map 也不起作用:有人可以指出我的错误并解释我做错了什么吗?也许显示其他方法来解决它?使用过滤器,减少或哪个更可取?单线解决方案是高度优选的。感谢您的回答!

最佳答案

您需要的是 Array.prototype.map,因为分配 el 不同于分配 arr[i](它不是改变数组):

arr2 = arr2.map(el => el === true ? false : true);

可以简化为:

arr2 = arr2.map(el => !el);

关于javascript - 当一个简单的 For Loop 工作正常时,我的 forEach 方法有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57956205/

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