Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

1.splice

splice(index, num)
index: 下标
num: 删除的数量
@return 删除的元素

原来的数组会被修改

删掉第三个元素
1
2
3
4
let dataSource = ["a", "b", "c"]
let newDataSource = dataSource.splice(2, 1);
console.log(newDataSource) // ["c"]
console.log(dataSource) //  ["a", "b"]
在for 循环使用

比如要依次删除 dataSource中的元素

1
2
3
4
5
6
let dataSource = ["a", "b", "c"]
for (let i = 0; i < dataSource.length; i ++) {
dataSource.splice(i, 1)
console.log(dataSource) // ["b", "c"], ["c"] , []
i = i - 1 // 原来的元素被删掉需要往前一位
}

2.slice

2.slice(startIndex, endIndex)
startIndex: 开始下标 必填
endIndex: 结束下标(不包含这个元素) 非必填
@return 截取的元素

原来的数组不会被修改

1
2
3
4
let dataSource = ["a", "b", "c"]
let newDataSource = dataSource.slice(1,2);
console.log(newDataSource) // ["b"]
console.log(dataSource) //  ["a", "b", "c"]

评论