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);}
This question is related to
javascript
arrays
delete foo[key];
:D
If you know the key name simply do like this:
delete array['key_name']
delete foo[key];
:D
This is how I would do it
myArray.splice( myArray.indexOf('bar') , 1)
If you know the key name simply do like this:
delete array['key_name']
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.
http://www.internetdoc.info/javascript-function/remove-key-from-array.htm
removeKey(arrayName,key);
function removeKey(arrayName,key)
{
var x;
var tmpArray = new Array();
for(x in arrayName)
{
if(x!=key) { tmpArray[x] = arrayName[x]; }
}
return tmpArray;
}
there is an important difference between delete and splice:
ORIGINAL ARRAY:
[<1 empty item>, 'one',<3 empty items>, 'five', <3 empty items>,'nine']
AFTER SPLICE (array.splice(1,1)):
[ <4 empty items>, 'five', <3 empty items>, 'nine' ]
AFTER DELETE (delete array[1]):
[ <5 empty items>, 'five', <3 empty items>, 'nine' ]
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.
delete foo[key];
:D
delete foo[key];
:D
Source: Stackoverflow.com