如何在javascript中取消设置数组中的元素? [英] How do I unset an element in an array in javascript?

查看:45
本文介绍了如何在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);
    }
}

这篇关于如何在javascript中取消设置数组中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆