簡體   English   中英

循環遍歷 JavaScript 中的嵌套數組

[英]Looping through a nested array in JavaScript

目前我有一個要循環的多維數組。 我想要的只是將內部元素推送到一個空數組。 但我得到的與預期的 output 完全不同。

到目前為止,所有人都在下面

 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()

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

你想完全展平你的數組,還是只從每個內部數組中取出第一項並將其復制到新數組中?

如果你想完全展平它,你可以這樣做:

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

如果您只想要每個內部數組中的第一項,我會推薦 Konstantin 建議的解決方案。

你不需要循環:

 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