javascript - 数组拼接产生意外结果

标签 javascript arrays

试图理解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/

相关文章:

javascript - 在 Nodejs 与 Redis 哈希中使用全局对象

javascript - JavaScript 中的默认属性设置(如 Lodash 源代码所示)

javascript - 循环遍历数组中的对象并向每个对象添加属性

python - 在 Python 中遍历多维数组

c++ - 动态数组中的数组循环终止

javascript - 将 javascript 数字转换为 UInt32 的技巧

javascript - 为什么我的 JavaScript 日期/时间对象在 Cloud Firestore 中存储为 map 而不是时间戳?

javascript - Azure 移动服务 HTML 5 用户身份验证在 IE(.NET 后端)中显示 Windows 安全对话框

c# - 在多维 System.Collection.IList 中快速查找

c - 如何在函数内为数组分配内存