splice 源码实现
时间: 2023-11-21 18:55:55 浏览: 45
以下是splice函数的源码实现:
```javascript
Array.prototype.splice = function(start, deleteCount, ...items) {
// 记录数组长度
const len = this.length;
// 处理start参数
let startIndex = start;
if (startIndex < 0) {
startIndex = Math.max(len + startIndex, 0);
} else {
startIndex = Math.min(startIndex, len);
}
// 处理deleteCount参数
let numToDelete = deleteCount;
if (numToDelete === undefined) {
numToDelete = len - startIndex;
} else {
numToDelete = Math.max(numToDelete, 0);
numToDelete = Math.min(numToDelete, len - startIndex);
}
// 备份删除的元素
const deletedElements = [];
for (let i = 0; i < numToDelete; i++) {
const index = startIndex + i;
const element = this[index];
deletedElements.push(element);
}
// 删除元素
const numToInsert = items.length;
const diff = numToInsert - numToDelete;
if (diff > 0) {
// 插入元素后数组变长
for (let i = len - 1; i >= startIndex + numToDelete; i--) {
this[i + diff] = this[i];
}
} else if (diff < 0) {
// 插入元素后数组变短
for (let i = startIndex + numToDelete; i < len; i++) {
this[i + diff] = this[i];
}
for (let i = len - 1; i >= len + diff; i--) {
delete this[i];
}
}
// 插入元素
for (let i = 0; i < numToInsert; i++) {
this[startIndex + i] = items[i];
}
// 返回删除的元素
return deletedElements;
};
```
该函数的作用是从数组中删除元素并向数组添加新元素,然后返回被删除的元素。splice函数的参数包括起始位置、要删除的元素数量和要添加到数组中的元素。在实现中,首先处理了起始位置和要删除的元素数量的参数,然后备份了要删除的元素,接着删除元素并插入新元素,最后返回被删除的元素。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)