How do I remove the key 'bar' from an array foo so that 'bar' won't show up in
for(key in foo){alert(key);}
How do I remove the key 'bar' from an array foo so that 'bar' won't show up in
for(key in foo){alert(key);}
Don't use delete as it won't remove an element from an array it will only set it as undefined, which will then not be reflected correctly in the length of the array.
If you know the key you should use splice i.e.
myArray.splice(key, 1);
For someone in Steven's position you can try something like this:
for (key in myArray) {
if (key == 'bar') {
myArray.splice(key, 1);
}
}
or
for (key in myArray) {
if (myArray[key] == 'bar') {
myArray.splice(key, 1);
}
}
An important note: JavaScript Arrays are not associative arrays like those you might be used to from PHP. If your "array key" is a string, you're no longer operating on the contents of an array. Your array is an object, and you're using bracket notation to access the member named <key name>. Thus:
var myArray = []; myArray["bar"] = true; myArray["foo"] = true; alert(myArray.length); // returns 0.
because you have not added elements to the array, you have only modified myArray's bar and foo members.