JS数组中的 splice() 方法

2022-08-06,,,

一、语法以及描述

说明:通过添加、删除、修改元素来修改数组
语法Array.splice(start[, deleteCount[, item1, …]])
参数

  1. start : 开始位置
  2. deleteCount : 删除的元素个数
  3. item, item2… : 添加的元素

返回值:始终是删除的元素集合,如果删除数量为 0,则返回空数组
是否改变原数组:是

二、参数

1. 只有一个参数start

说明start 表示从此位置开始删除元素,一直到数组结尾
返回值:从 start 开始至数组结位置的所有元素
原数组:从 0 开始到 start 位置的元素
示例

var arr = ['A', 'B', 'C', 'D'];

var res = arr.splice(1)
console.log(res);
// ["B", "C", "D"]
console.log(arr);
// ['A']
2. 有两个参数start、deleteCount

说明
  start表示从此位置开始删除元素。
  deleteCount 表示删除的元素个数
  deleteCount 取值
    负数 : 不删除任何元素
    为 0 : 不删除任何元素
    大于数组长度 : 将会删除 start 之后的所有元素
    有效个数 n : 将会删除从 start 开始删除元素,删除 n 个

返回值:从 start 开始删除的元素集合
原数组:删除后剩余的元素集合
示例

var colors = ['red', 'yellow', 'green', 'pink'];

// 1. deleteCount 为 0 或者 负数
var res = colors.splice(1, 0);
console.log('res',res)
// []
console.log('colors',colors)
// ['red', 'yellow', 'green', 'pink']

// 2. deleteCount 为有效值
var res = colors.splice(1, 2);
console.log('res2',res)
// ["yellow", "green"]
console.log('colors',colors)
// ["red", "pink"]
3. 有三个及以上参数start、deleteCount、item...

说明
  start表示从此位置开始删除元素。
  deleteCount 表示删除的元素个数
  deleteCount 取值
    负数 : 不删除任何元素
    为 0 : 不删除任何元素
    大于数组长度 : 将会删除 start 之后的所有元素
    有效个数 n : 将会删除从 start 开始删除元素,删除 n 个
  item 表示添加到数组中的元素,从 start 位置开始添加

返回值:从 start 开始删除的元素集合
原数组:先删除元素、再添加元素后的数组集合
示例

var numbers = [1, 2, 3, 4, 5]

// 1. 删除个数为0、直接添加
// var res = numbers.splice(1, 0, 8)
// console.log(res)
// []
// console.log(numbers)
// [1, 8, 2, 3, 4, 5]

// 2. 先删除、后添加
var res = numbers.splice(1, 1, 8)
console.log(res)
// [2]
console.log(numbers)
// [1, 8, 3, 4, 5]

三、注意

  1. 无论是删除元素还是添加元素, 该方法的返回值始终是删除的元素集合
  2. 如果添加元素时没有删除元素, 则返回空数组

本文地址:https://blog.csdn.net/weixin_45046594/article/details/107285708

《JS数组中的 splice() 方法.doc》

下载本文的Word格式文档,以方便收藏与打印。