简体   繁体   中英

How to access an element in each array?

Let's assume that a random array has given:

let myArray = [[1, 2, 3, 5], [3, 4, 5], [2, 5]];

I want to access each element in array like this:

[myArray[0][0], myArray[1][0], myArray[2][0]] // [1, 3, 2]
[myArray[0][0], myArray[1][0], myArray[2][1]] // [1, 2, 5]
[myArray[0][0], myArray[1][1], myArray[2][0]] // [1, 4, 2]
[myArray[0][0], myArray[1][1], myArray[2][1]] // [1, 4, 5]
...
[myArray[0][3], myArray[1][2], myArray[2][1]] // [5, 5, 5]

like this

I know I can do this by using for loop, but the given array may change. Array length and data may different at each time. I want to solve this even if the given array is different. How can I solve this?

Sorry I'm not a English native speaker.

You can use .forEach

const arr = [[1, 2], [3, 4, 5], [6, 7], [8]];
arr.forEach((item) => {
  item.forEach((child) => {
    console.log(child);
  });
})

You can use flat() just for that, it will works for any array depth:

const myArray = [[1, 2, 3, 5], [3, 4, 5], [2, 5]].flat();
const deepArray =  [1, 1, [2, 2], [[3, [4], 3], 2]].flat()

// then you can access every array element with a simple foreach
myArray.forEach(element => console.log(element))
deepARray.forEach(element => console.log(element))

Here's a jsfiddle that show how to use it

Check this demo. It's about selection from array https://js-demo.com/index.php?ref=1d3ed9baff05

myArray.length tells you how many elements it has.

Similarly, myArray[0].length tells you how many elements the first one has, and so on.

You can use that to control your loops.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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