How do I unset an element in an array in javascript?

前端 未结 6 460
闹比i
闹比i 2020-12-01 03:13

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);}
6条回答
  •  臣服心动
    2020-12-01 03:48

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

    or

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

提交回复
热议问题