试图理解Array.splice() .
deleteCount: An integer indicating the number of old array elements to remove.
好的。看起来很简单。我想删除数组中的最后 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)
关于javascript - 数组拼接产生意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53709680/