Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 如何从JavaScript中的数组中删除特定元素?(How do I remove a particular element from an array in JavaScript?)

I have an array of numbers, and I'm using the .push() method to add elements to it.

(我有一个数字数组,并且正在使用.push()方法向其中添加元素。)

Is there a simple way to remove a specific element from an array?

(有没有一种简单的方法可以从数组中删除特定元素?)

The equivalent of something like array.remove(number);

(等价于array.remove(number);)

.

(。)

I have to use core JavaScript - frameworks are not allowed.

(我必须使用核心 JavaScript-不允许使用框架。)

  ask by Walker translate from so

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

1 Reply

0 votes
by (71.8m points)

Find the index of the array element you want to remove using indexOf , and then remove that index with splice .

(使用indexOf查找要删除的数组元素的index ,然后使用splice删除该索引。)

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

(splice()方法通过删除现有元素和/或添加新元素来更改数组的内容。)

 var array = [2, 5, 9]; console.log(array); var index = array.indexOf(5); if (index > -1) { array.splice(index, 1); } // array = [2, 9] console.log(array); 

The second parameter of splice is the number of elements to remove.

(splice的第二个参数是要删除的元素数。)

Note that splice modifies the array in place and returns a new array containing the elements that have been removed.

(请注意, splice会在适当位置修改数组,并返回一个包含已删除元素的新数组。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...