PDA

View Full Version : deleting element in array using myArray['string_key']='string_value' syntax?


robkar97
02-16-2008, 11:18 AM
I can't get simple array handling to function. Consider an array "myArray" that holds name/value pairs like so

var myArray = new Array();
myArray['first'] = 'this is a string';
myArray['the_second'] = 'this is another string';
myArray['any_string'] = 'hello world';

Now, myArray.length returns 0!

With

for (i in myArray) alert(i + ' =' + myArray[i]) I still get all three elements...

Also, myArray.spliice('the_second', 1) doesn't work - the array is left untouched.

:eek:
Robert

YMas
02-16-2008, 06:59 PM
Hello,
Actually you've defined an associative array.

The key/value pairs you have defined are not counted as elements of an array, this is why you get 0 for myArray.length.

Try alerting ' i ' only, you should get 'first', 'the_second' and 'any_string'.

This (http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/) article may help.

Thanks,
YMas

robkar97
02-16-2008, 09:33 PM
Thanks Ymas!

I'll find another way of doing the same thing.

Robert