Removing an element from an array specifying a value in Javascript

前端 未结 5 476
独厮守ぢ
独厮守ぢ 2020-12-10 15:13

I have read this question:

Deleting array elements in JavaScript - delete vs splice

And it appears that both splice and delete require an index of the elemen

5条回答
  •  半阙折子戏
    2020-12-10 15:43

    You want to use the splice() function to remove the item, indexOf will find it in the array:

    To Find a specific element in the Array: (to know which to remove)

    var index = array.indexOf('test2'); 
    

    Full Example:

    var array = ['test1', 'test2', 'test3'];
    var value_to_remove = 'test2';
    array.splice(array.indexOf(value_to_remove), 1); 
    

    Working Demo

提交回复
热议问题