阵列拼接,结果出乎意料

时间:2018-12-10 16:24:43

标签: javascript arrays

试图了解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}]

1 个答案:

答案 0 :(得分:5)

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

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)