试图了解Array.splice()


  deleteCount:一个整数,指示要删除的旧数组元素的数量。


好。似乎很简单。我想删除数组中的最后4个对象。我希望与元素相同吗?

arr.splice(<start>, deleteCount<how-many-to-remove>):


// {0 - 8} is an example of object position
let obArr = [{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}]

// Start from the last and remove four:
obArr.splice(-1, 4)

console.log(obArr) // not expected.

console.log(obArr) // expected: [{0}, {1}, {2}, {3}]

最佳答案

您的代码从最后一项开始,并尝试删除最后一项之后的四个值。但是最后一项之后没有四个值。如果要从末尾删除四个,请从数组的开头开始:



let obArr = [0, 1, 2, 3, 4, 5, 6, 7]

// Start from the 4th last and remove four:
obArr.splice(-4, 4)

console.log(obArr) 

09-11 01:40