# 如何模拟实现 Array.prototype.splice
Array.prototype._splice = function (start, deleteCount, ...addList) {
// 如果start为负数,那么就从倒数的元素算起
if (start < 0) {
if (Math.abs(start) > this.length) {
start = 0
} else {
start += this.length
}
}
// 如果没有传deleteCount,那么默认
if (typeof deleteCount === 'undefined') {
deleteCount = this.length - start
}
// 删除的元素列表
const removeList = this.slice(start, start + deleteCount)
// 删除元素右侧的元素列表
const right = this.slice(start + deleteCount)
let addIndex = start
addList.concat(right).forEach(item => {
this[addIndex] = item
addIndex++
})
this.length = addIndex
// 返回删除列表
return removeList
}
← js实现单向链表 前端错误监控与错误上报 →