gpt4 book ai didi

javascript - 两个foreach替换JS

转载 作者:行者123 更新时间:2023-11-30 07:19:51 25 4
gpt4 key购买 nike

您能否推荐更优雅的处理这些案例的方法?

const arr1 = [1, 2, 3];
const arr2 = ['a', 'b', 'c'];

const getCombinations = () => {
const combinations = [];
arr1.forEach(el1 => {
arr2.forEach(el2 => {
combinations.push({
el1,
el2
});
});
});
return combinations;
};

console.log(getCombinations());

最佳答案

您可以使用 Array.flatMap()Array.map() :

const arr1 = [1, 2, 3];
const arr2 = ['a', 'b', 'c'];

const getCombinations = (a, b) =>
a.flatMap(el1 => b.map(el2 => ({ el1, el2 })));

const result = getCombinations(arr1, arr2);

console.log(result);

关于javascript - 两个foreach替换JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54225406/

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