我不确定使用的术语(我认为它被称为“lambda”或类似的东西),所以我无法进行适当的搜索。
Python 中的以下行:
a, b, c, d, e = [SomeFunc(x) for x in arr]
我怎样才能在 Javascript 中做同样的事情?
我有这个开始:
let [a, b, c, d, e] = arr;
但我仍然需要对 arr
中的每个元素调用 SomeFunc
。
最佳答案
一个近似的方法是使用数组方法 map
.它使用函数对每个数组元素执行操作,并返回一个相同长度的新数组。
const add2 = (el) => el + 2;
const arr = [1, 2, 3, 4, 5];
let [a, b, c, d, e] = arr.map(add2);
console.log(a, b, c, d, e);
使用数组解构时要小心,以确保解构返回数组的元素数量正确。
关于javascript - 如何将这个 "one-line for loop"从 Python 移植到 JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48525768/