js手写数组remove

前言

  在ES5到ES11技术不断的更新中,关于数组的操作却始终没有像Java数组remove那么方便的API供我们使用,所以我特地查看了许多文章学习了一下,总结出最方便也最高效率的操作方式;

案例

Array.prototype.remove = function(from,to){//直接在Array的原型对象上创建,这样全局的数组都可以直接.remove使用
  let rest = this.slice((to || from) + 1 || this.length);//这个作用在于截取我们给与的下标之后的数组部分
  this.length = from < 0 ? this.length + from : from;//这个就是把原先的数组截取到from开始的长度,注意这里this指向的是调用该数组的地址
  // return this.push.apply(this,rest);//这个方法就是对于数组的拼接,面试的时候这样写如果面试官是高级工程师以下的级别可能会对你的写法眼前一亮,但实际对于大数组不友好,不建议使用
  return this.push(...rest);//这里就是把截取的数组内的值取出来,重新放入原先的数组内,数组大小不超过10w就优先用这种
  // return rest.filter(v=>this.push(v));//10w以上就用这种
}
let arr = [1,2,3,4,5,6,7,8,9];
arr.remove(-1);
console.log(arr);//[ 1, 2, 3, 4, 5, 6, 7, 8 ]
arr.remove(2);
console.log(arr);//[ 1, 2, 4, 5, 6, 7, 8, 9 ]
arr.remove(2,3);
console.log(arr);//[ 1, 2, 5, 6, 7, 8, 9 ]
// 如果是超出浏览器临界值的数组大小
let arr = new Array(125624).fill(6);
arr.remove(2,3);
console.log(arr);//Maximum call stack size exceeded
// 如果是超出浏览器临界值的数组大小,但使用rest.filter(v=>this.push(v));
let arr = new Array(125624).fill(6);
arr.remove(2,3);
console.log(arr);//... 125522 more items ]

总结

  不同浏览器的临界值其实都不尽相同,this.push.apply的方式和this.push(...rest)的方式只是性能方面后者略快一点,但相差并不大。有人可能会好奇为什么不用concat或者拓展运算符拼接的方式,这两种方式都是创建了一个新的数组,而不是在原数组的基础上进行整改,所以封装的方法到时候得把新数组return出去的同时再替换原数组的值,这种方式对程序的栈空间以及执行时间都不如上面的方式友好。

原文地址:https://www.cnblogs.com/zxd66666/p/13407501.html