简体   繁体   English

如何访问每个数组中的元素?

[英]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.我知道我可以通过使用 for 循环来做到这一点,但给定的数组可能会改变。 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你可以使用.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:您可以为此使用flat() ,它适用于任何数组深度:

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这是一个展示如何使用它的jsfiddle

Check this demo.检查这个演示。 It's about selection from array https://js-demo.com/index.php?ref=1d3ed9baff05这是关于从数组中选择https://js-demo.com/index.php?ref=1d3ed9baff05

myArray.length tells you how many elements it has. myArray.length 告诉您它有多少个元素。

Similarly, myArray[0].length tells you how many elements the first one has, and so on.同样,myArray[0].length 告诉您第一个有多少个元素,依此类推。

You can use that to control your loops.您可以使用它来控制循环。

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

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