简体   繁体   English

在Javascript中打印出子数组的元素

[英]print out elements of sub-array in Javascript

I don't understand how to find the length of a subarray in Javascript. 我不明白如何在Javascript中找到子数组的长度。 Here is an example from an exercise: 以下是练习中的示例:

 var table = [
["Person",  "Age",  "City"],
["Sue",     22,     "San Francisco"],
["Joe",     45,     "Halifax"]
];

I have tried to print out the elements of the sub-arrays individually using these for loops: 我试图使用这些for循环单独打印出子数组的元素:

for(person in table) {
    for(var i = 0; i < table[person].length; i++);
        console.log(table[person][i]);
}

but it seems that 但似乎是这样

table[person].length

is not valid syntax although 虽然是无效的语法

table.length 

is valid and 是有效的

table[person][i]

returns the element at the sub-index table_person_i 返回子索引table_person_i的元素

You should use nested for loops for this task: 您应该为此任务使用嵌套for循环:

for (var i = 0; i < table.length; i++) {
    for (var j = 0; j < table[i].length; j++) {
        console.log(table[i][j]);
    }
}

Try this: 尝试这个:

for (var j = 0; j<table.length; j++) 
{
     //j(th) element of table array
     for (var i = 0; i < table[j].length; i++)
     {
         //i(th) element of j(th) element array
         console.log(table[j][i]);
     }
}

That's an array, not an object, so you can't use for/ in loops. 这是一个数组,而不是一个对象,所以你不能使用for / in循环。 Use the regular for loop instead. 请改用常规for循环。

//for (person in table) {

for (var person = 1; person < table.length; person++) {
    for(var i = 0; i < table[person].length; i++)
    {
        console.log(table[person][i]);
    }
}

In your example, your array is an array of array. 在您的示例中,您的数组是一个数组数组。 To fetch person's names, and according your example: 要获取人名,并根据您的示例:

for (var i = 1; i < table.length; i++)
{
 console.log(table[i][0]); // first element of each sub array
}

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

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