I don't understand how to find the length of a subarray in 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(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].length
is valid syntax. Why do you iterate over the array with afor...in
loop? Using afor
loop might fix your problem. – Felix Kling Dec 21 '13 at 17:55for...in
for arrays. See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. And only because Codecademy doesn't like your code doesn't mean it is syntactically invalid. – Felix Kling Dec 21 '13 at 18:04table[person]
withtable['person']
.person
is a variable containing values such as"0"
,"1"
, etc. So you end up doingtable["0"].length
, exactly matches the structure. It gets the length of the first element intable
. – Felix Kling Dec 21 '13 at 18:05