Remove Array Value By index in jquery

前端 未结 5 868
别那么骄傲
别那么骄傲 2020-12-14 15:05

Array:

var arr = {\'abc\',\'def\',\'ghi\'};

I want to remove above array value \'def\' by using index.

5条回答
  •  难免孤独
    2020-12-14 15:37

    Your syntax is incorrect, you should either specify a hash:

    hash = {abc: true, def: true, ghi: true};
    

    Or an array:

    arr = ['abc','def','ghi'];
    

    You can effectively remove an item from a hash by simply setting it to null:

    hash['def'] = null;
    hash.def = null;
    

    Or removing it entirely:

    delete hash.def;
    

    To remove an item from an array you have to iterate through each item and find the one you want (there may be duplicates). You could use array searching and splicing methods:

    arr.splice(arr.indexOf("def"), 1);
    

    This finds the first index of "def" and then removes it from the array with splice. However I would recommend .filter() because it gives you more control:

    arr.filter(function(item) { return item !== 'def'; });
    

    This will create a new array with only elements that are not 'def'.

    It is important to note that arr.filter() will return a new array, while arr.splice will modify the original array and return the removed elements. These can both be useful, depending on what you want to do with the items.

提交回复
热议问题