JS 数组常用方法

JS 数组常用方法

splice

splice() 方法用于添加或删除数组中的元素。

array.splice(index,deleteCount,item1,.....,itemX):array
- index:必需。规定从何处添加/删除元素。坐标从0开始
- deleteCount:可选,规定应该删除多少个元素,可以是0,表示不删除,如果不设置,表示删除从index到数组结束所有元素
- item:可选,从index处要添加到数组的新元素

返回:如果从数组中删除了元素,返回含有被删除的元素的数组

Example:

const myArr = ['Libai', 'Hanyu', 'Liuzhongyuan'];
console.log('start:',myArr)

// delete elements
var ret = myArr.splice(1, 1);
console.log('delete elements:'+ret);
console.log('current:',myArr)

// add elements
ret = myArr.splice(1,0,'Shushi','Shuzhe')
console.log('delete elements:'+ret);
console.log('current:',myArr)

// modify elemnt (先删后加)
ret = myArr.splice(0,1,'Dufu')
console.log('delete elements:'+ret);
console.log('current:',myArr)

// start: [ 'Libai', 'Hanyu', 'Liuzhongyuan' ]
// delete elements:Hanyu
// current: [ 'Libai', 'Liuzhongyuan' ]
// delete elements:
// current: [ 'Libai', 'Shushi', 'Shuzhe', 'Liuzhongyuan' ]
// delete elements:Libai
// current: [ 'Dufu', 'Shushi', 'Shuzhe', 'Liuzhongyuan' ]
posted @ 2023-11-12 14:18  寒小韩  阅读(6)  评论(0编辑  收藏  举报