Javascript gets the length of the subarray

I was wondering if there is a way to get the length of a second level array, for example:

var arr = new Array(); arr[0] = new Array(); arr[0][0] = 'a'; arr[0][1] = 'a'; arr[0][2] = 'a'; 

I tried this, but to no avail:

 arr[0].length; 

Hurrah!

EDIT

The evil code is as follows.

This is the function that I use to populate an array that works as expected:

 function input_text(action, id) { if (action == 'add') { var i = info.length; if (i != 0) i++; info[i] = new Array(); info[i]['type'] = 'input'; info[i]['subtype'] = 'text'; info[i]['nome'] = $('#input_text_form input[name="input_text_nome"]').val(); info[i]['name'] = $('#input_text_form input[name="input_text_name"]').val(); info[i]['id'] = $('#input_text_form input[name="input_text_id"]').val(); info[i]['maxlenght'] = $('#input_text_form input[name="input_maxlenght"]').val(); info[i]['default'] = $('#input_text_form input[name="input_text_default"]').val(); info[i]['js'] = $('#input_text_form input[name="input_text_js"]').val(); } } 

.. and this is a function to build a JSON string from an array. You may notice that I counted the length of an array of sublevels several times to prevent an incorrect string, for example ,}

 function toJSON () { var fll = info.length; var sll = 0; var tll = 0; var i; var x; var z; var w; var b; json = '{'; for (i in info) { json += '"'+i+'":{'; sll = info[i].length; alert(sll); z = 0; for (x in info[i]) { if ($.isArray(info[i][x])) { json += '"'+x+'":{'; tll = info[i][x].length; w = 0; for (b in info[i][x]) { tll == w ? json += '"'+b+'" : "'+info[i][x][b]+'"' : json += '"'+b+'" : "'+info[i][x][b]+'",'; w++; } sll == z ? json += '}' : json += '},'; } else { sll == z ? json += '"'+x+'" : "'+info[i][x]+'"' : json += '"'+x+'" : "'+info[i][x]+'",'; } z++; } fll == i ? json += '}' : json += '},'; } json += '}'; } 

Every time I print the value of any of the variables fll, sll and tll, it gives me zero.

+4
source share
3 answers

You essentially create an object with string indexes. You can only get the length if it is a true array.

 arr[0] = []; arr[0][0] = 134; arr[0][1] = 264; arr[0].length; // will work arr[1] = {}; arr[1]['str1'] = 134; arr[1]['str2'] = 256; arr[1].length; // will not work 

See this question for more information: JavaScript Object Length

+5
source

You are mistaken? Try:

 arr[0].length; 
+2
source

This works for me:

 var arr = new Array(); arr[0] = new Array(); arr[0][0] = 'a'; arr[0][1] = 'a'; arr[0][2] = 'a'; console.log(arr[0].length); 

Result:

 3 

Check yourself here.

+2
source

All Articles