Skip to content

Instantly share code, notes, and snippets.

@xinlc
Last active May 15, 2018 08:14
Show Gist options
  • Save xinlc/25ef2f2fb81885f7fde0f20083e4993b to your computer and use it in GitHub Desktop.
Save xinlc/25ef2f2fb81885f7fde0f20083e4993b to your computer and use it in GitHub Desktop.
JS 数组删除元素
// 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);
};
// 移除数组中的第二项
// array.remove(1);
// 移除数组中的倒数第二项
// array.remove(-2);
// 移除数组中的第二项和第三项(从第二项开始,删除2个元素)
// array.remove(1,2);
// 移除数组中的最后一项和倒数第二项(数组中的最后两项)
// array.remove(-2,-1);
// 原理:通过元素在数组的下标位置来定位删除
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment