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

前端 未结 6 445
闹比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:42

    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;
    }
    
    0 讨论(0)
  • 2020-12-01 03:45

    If you know the key name simply do like this:

    delete array['key_name']
    
    0 讨论(0)
  • 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);
        }
    }
    
    0 讨论(0)
  • 2020-12-01 03:57

    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.

    0 讨论(0)
  • 2020-12-01 03:59

    This is how I would do it

     myArray.splice( myArray.indexOf('bar') , 1) 
    
    0 讨论(0)
  • 2020-12-01 04:00
    delete foo[key];
    

    :D

    0 讨论(0)
提交回复
热议问题