简体   繁体   English

循环遍历 JavaScript 中的嵌套数组

[英]Looping through a nested array in JavaScript

Presently I have a multidimensional array that I want to loop over.目前我有一个要循环的多维数组。 All I want is to push the inner elements to an empty array.我想要的只是将内部元素推送到一个空数组。 But What I'm getting is totally different from the expected output.但我得到的与预期的 output 完全不同。

All have done so far below到目前为止,所有人都在下面

 const prices = [ [2, 20], [7, 50], [12, 100], [17, 40], [22, 32], [27, 25 ] ]; function addItemToCart() { let new_items = [] // I want this array to be [2, 7, 12, 17, 22, 27] // looping outer array elements for(let i = 0; i < prices.length; i++) { for(let j = 0; j < prices[i].length; j++) { new_items.push(prices[i][j]) console.log(new_items); } } } addItemToCart()

Use map: const newItems = prices.map(price => price[0])使用 map: const newItems = prices.map(price => price[0])

Do you want to completely flatten your array, or just take the first item from each inner array and copy that to the new array?你想完全展平你的数组,还是只从每个内部数组中取出第一项并将其复制到新数组中?

If you want to flatten it completely, you can do it like this:如果你想完全展平它,你可以这样做:

const newArray = prices.reduce((res, arr) => [...res, ...arr], []);

If you only want the first item from each inner array, I would recommend the solution that Konstantin suggested.如果您只想要每个内部数组中的第一项,我会推荐 Konstantin 建议的解决方案。

You don't need loops for that:你不需要循环:

 const prices = [ [2, 20], [7, 50], [12, 100], [17, 40], [22, 32], [27, 25 ] ]; const toAdd = [].concat.apply([], prices); console.log(toAdd);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM