Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

javascript - 如何从值中删除数组中的项目?(How to remove item from array by value?)

Is there a method to remove an item from a JavaScript array?

(有没有一种方法可以从JavaScript数组中删除项目?)

Given an array:

(给定一个数组:)

var ary = ['three', 'seven', 'eleven'];

I would like to do something like:

(我想做类似的事情:)

removeItem('seven', ary);

I've looked into splice() but that only removes by the position number, whereas I need something to remove an item by its value.

(我已经研究过splice()但是它只能通过位置编号删除,而我需要一些东西才能通过其值删除项目。)

  ask by MacMac translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the indexOf method like this:

(您可以像这样使用indexOf方法 :)

var index = array.indexOf(item);
if (index !== -1) array.splice(index, 1);

Note : You'll need to shim it for IE8 and below

(注意您需要对IE8及以下版本进行填充)

 var array = [1,2,3,4] var item = 3 var index = array.indexOf(item); if (index !== -1) array.splice(index, 1); console.log(array) 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...