Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

How to read out the inner array length of a 2 dimensional array in javascript

I need to detect the length of an inner array within a 2d array in my application. But unfortunately it always raises a "TypeError: Cannot read property 'length' of undefined" error. Does anyone detect an error? Thanks a bunch

This is the 2d array called currentNodeData (I get this with the following command --> console.log(currentNodeData)):

enter image description here

And this is how I want to receive the length of the inner array, which should be 6:

console.log(currentNodeData[0].length);

And this is the error:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

what is currentNodeData in your case?

lets review:

So we have an Array inside the array.

Lets name it :

const innerArray = [{id:1}, {id: 2}, {id: 3}, {id: 4}]
const outer = [innerArray];

the outer array will have only one inner array? if yes: we can do the next thing:

outer[0].length // 4

or we can use flat()

outer.flat().length // 4

const innerArray = [{id:1}, {id: 2}, {id: 3}, {id: 4}]
const outer = [innerArray];

console.log(outer[0].length);
console.log(outer.flat().length);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...