簡體   English   中英

映射嵌套數組?

[英]Mapping over nested array?

抱歉這個菜鳥問題,但我想知道如何在陣列前面有一個數字的陣列上進行 map?

array = [
            ['geeks', '4', 'geeks' ],
            ['Hello', 'test', 'jeff'],
            ['Test', 'Pli', 'alphabet']
        ]

我正在嘗試循環在我的控制台中像這樣輸出的數據

我需要循環顯示所有 arrays 的數據

下面將打印二維數組上的每個字符串

array.forEach((childArr) => childArr.forEach((str) => console.log(str)))

您的控制台在每個元素內容之前顯示索引。

在您的情況下,每個元素也是一個數組。

因此,對於映射您的特定數組:

let newArray = array.map(innerArray => innerArray.map(element => {你的代碼}));

因此,chrome 中 DevTools 中數組旁邊的數字只是用來告訴您數組中有多少項。

這不是實際的數組

如果您想編輯數組或僅訪問元素,有多種方法

看這個例子:

 let someArray = [ [1,"a",2.3], [2,"b",7.8], [3,"c",4.5], ] // if you want to change the items inside the array //Array.map someArray = someArray.map(innerArray =>{ return innerArray.map(element => { //Do any thing to the element lets say that we want to convert all values to strings return String(element); }) }) console.log(someArray); console.log('##################################'); //if you don't want to change the items inside the arreay you can: // 1. remove the return statement from the Array.map function above // 2. use any type of loop for, while loop for(let i = 0; i < someArray.length; i++){ for(let j = 0; j < someArray[i].length; j++){ // Do any thing with the array item lets say you want to print it console.log(someArray[i][j]); } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM