r1si
r1si

Reputation: 1164

Array length in Javascript chrome error

I have a very strange problem with js console in chrome, if i go in chrome console and write :

var numero = new Array(["/php/.svn/tmp", "/php/.svn/props"]);

return me "undefined" so i think numero is an array with 2 elements, but if i write:

numero

returns:

[Array[2]]

after

numero.length

and return 1 ..... why? don't return 2 ??? where am I doing wrong? can i give a method that returns 2? thanks in advance

EDIT: I will explain my problem. I have a function that return this when i selected 2 items :

myFolders.getSelected()
["/php/.svn", "/php/upload.php"]

and this when selected one items:

myFolders.getSelected()
"/php/upload.php"

as u note the second one isn't an array.

now i use this method to activate on change selected item an calculate a global variable:

function calcoloNumeroElementi(){
    var numero = new Array(myFolders.getSelected());
    numeroElementiSelezionati = numero[0].length;
}

but returns always 1 or the number of characters when i selected only one items.

Upvotes: 0

Views: 1369

Answers (3)

suff trek
suff trek

Reputation: 39767

Don't use New Array, use just literal notation:

var numero = ["/php/.svn/tmp", "/php/.svn/props"];

Update (Based on your comments)

If you have your function myFolders.getSelected() that returns a single string and you want to add it to array, you can do this either declaratively:

var numero = [myFolders.getSelected()]

Or, if you plan to add multiple values, e.g. in a loop, you can push new value into array

var numero = [];
...
numero.push(myFolders.getSelected());

Upvotes: 0

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

You're creating an array inside other array, that's why it returns 1.

console.log( numero[0].length ); // 2

So it should be:

var numero = ["/php/.svn/tmp", "/php/.svn/props"];

or

var numero = new Array("/php/.svn/tmp", "/php/.svn/props"); // without `[` and `]`

Then use console.log( numero.length );

Upvotes: 5

gbtimmon
gbtimmon

Reputation: 4322

["/php/.svn/tmp", "/php/.svn/props"] returns an array containing the two strings.

new Array(arg0, arg1 ... argn); returns an array with the elements defined as the arguments

new Array(["/php/.svn/tmp", "/php/.svn/props"]); will return an array where the first elements is and array of two strings.

Try instead numero[0].length and see what you get.

Or istead define your array just like this var numero = ["/php/.svn/tmp", "/php/.svn/props"];

Upvotes: 0

Related Questions