Page 1 of 1
How to check against a value in an array?
Posted: Fri May 08, 2009 7:15 am
by lovelf
Code: Select all
var b = 'valc';
var a = new Array();
a["vala"] = 0.044; a["valb"] = 0.057; a["valc"] = 0.056;
How to retrieve from the array the value of var b which it's value on the array is 0.056 ?
var b can be set to 'vala', or 'valb', which are written on the array as 0.044, and 0.057
Thanks.
Re: How to check against a value in an array?
Posted: Fri May 08, 2009 8:14 am
by Apollo
Re: How to check against a value in an array?
Posted: Fri May 08, 2009 12:14 pm
by kaszu
In javascript arrays can't have keys like strings, this is why:
Code: Select all
var a = new Array();
a["asd"] = 5;
alert(a.length); //alerts 0
Better use object for that instead.
Re: How to check against a value in an array?
Posted: Thu May 14, 2009 5:26 am
by lovelf
kaszu, I was looking for
Code: Select all
var c = 'asd';
var a = new Array();
a["asd"] = 5;
alert(a[c]); //alerts 5
Re: How to check against a value in an array?
Posted: Sat May 16, 2009 7:32 am
by kaszu
Yes, what I mean is you are using Array instead of {} , which is incorrect, because Array can't handle non integer keys and it has additional functions, which won't work anymore. Array doesn't give you any benefit, but can complicate debugging later.
I'm just saying that for this purpose Object should be used.
Code: Select all
var c = 'asd';
var a = {};
a["asd"] = 5;
alert(a[c]); //alerts 5
Re: How to check against a value in an array?
Posted: Sat May 16, 2009 8:15 am
by VladSun
[js]a['b'] = 'c'[/js]
is an object construction/operation indeed.
Equivalent of
[js]a.b = 'c'[/js]
And an Array is also an object.
Re: How to check against a value in an array?
Posted: Sat May 16, 2009 4:15 pm
by kaszu
That's true.
Other developers may not know that somewhere in a script it's used as object and may try to use array function ('shift', 'pop', 'splice', 'length', etc.) which will return unexpected value as a result.
I consider it as a bad practice to use Array where Object is needed.