• 欢迎来到本站,本站主要做程序员相关技术、博客、笔记,如果喜欢本网站那么赶紧使用Ctrl+D 收藏吧!
  • 如果有任何疑问,可以在下方文章下方留下你的评论~

[JavaScript] Remove a specific item in array

电子书籍 8个月前 (10-04) 2次浏览 0个评论

How to delete an element of an array in JavaScript, you need to know the splice function.

splice

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

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

Remove a specific item from an array

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

var arr = ['a','b','c','d'];
arr.splice(1,1);
console.log(arr);
//['a','c','d'];

var arr2 = ['a','b','c','d']
arr2.splice(1,2);
console.log(arr2);
//['a','d']

or

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

Examples

// Remove the second item in the array
array.remove(1);
// Remove the penultimate item from the array
array.remove(-2);
// Remove the second and third items in the array (starting with the second item, remove 2 elements)
array.remove(1,2);
// Remove the last and penultimate items in the array (the last two items in the array)
array.remove(-2,-1);

中国笔友, 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:[JavaScript] Remove a specific item in array
喜欢 (0)
发表我的评论
取消评论
表情 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址