js数组删除指定索引
时间: 2023-11-25 07:08:32 浏览: 93
在JavaScript中,要删除数组中的指定索引,可以使用splice()方法或自定义方法remove()来实现。
使用splice()方法的示例代码如下:
```javascript
var arr = [1, 2, 3, 4, 5, 6, 7]; //源数据
var delIndex = [3, 2, 4]; //需要删除源数据的所有索引
for (var i = delIndex.length - 1; i >= 0; i--) {
arr.splice(delIndex[i], 1);
}
console.log(arr); // [1, 2, 6, 7]
```
上述代码中,通过使用splice()方法从后往前删除数组元素,确保删除元素后的索引不会发生错位。
另一种方法是自定义remove()方法,示例代码如下:
```javascript
Array.prototype.remove = function(dx) {
if (isNaN(dx) || dx > this.length) {
return false;
}
for (var i = 0, n = 0; i < this.length; i++) {
if (this[i != this<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [JS删除指定索引的数组](https://blog.csdn.net/qq_36800701/article/details/80214766)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [JS 移除数组中指定索引项](https://blog.csdn.net/heyangyi_19940703/article/details/52449153)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文