gpt4 book ai didi

javascript - 通过对每对值执行操作将两个数组组合成一个数组

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

有两个长度相同的数组:

firstArray = [22, 54, 33, 10];
secondArray = [2, 27, 11, 10];

我想通过将第一个数组的每个元素除以第二个数组中的对来获得第三个数组,在这种情况下,结果应该是:

resultArray = [11, 2, 3, 1];

我尝试使用 foreach()map() 来做到这一点,但我得到的只是未定义的值。例如这段代码:

firstArray.forEach(index) => {
resultArray[index] = firstArray[index] / secondArray[index];
});

有什么建议吗?

最佳答案

您可以映射 firstArray 的迭代结果,并使用索引获取 secondArray 的值。

var firstArray = [22, 54, 33, 10],
secondArray = [2, 27, 11, 10],
result = firstArray.map((v , i) => v / secondArray[i]);

console.log(result);

另一种解决方案,可能是将所有数组收集到一个数组中并减少数据。

var firstArray = [22, 54, 33, 10],
secondArray = [2, 27, 11, 10],
result = [firstArray, secondArray].reduce((a, b) => a.map((v , i) => v / b[i]));

console.log(result);

关于javascript - 通过对每对值执行操作将两个数组组合成一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49032607/

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