如何在javascript中取消设置数组中的元素?

如何在javascript中取消设置数组中的元素?

问题描述:

如何从数组 foo 中删除键 'bar' 以便 'bar' 不会出现在

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);}

不要使用 delete 因为它不会从数组中删除元素,它只会将其设置为未定义,这将那么就不能正确反映在数组的长度中.

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.

如果您知道密钥,您应该使用 splice

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 (var key in myArray) {
    if (key == 'bar') {
        myArray.splice(key, 1);
    }
}

for (var key in myArray) {
    if (myArray[key] == 'bar') {
        myArray.splice(key, 1);
    }
}