gpt4 book ai didi

javascript - 如何在 for 循环内将新项目附加到同一数组中的同一索引

转载 作者:行者123 更新时间:2023-12-03 04:55:49 24 4
gpt4 key购买 nike

我有数组的 obj

var data = [{
value: 1,
t: 1487203500000
}, {
value: 2,
t: 1487213700000
}];

这里,我需要在循环内比较 t obj ,如果超过 5 分钟,那么我需要创建一个值为 null 的一项并将其追加到该数组中。

预期结果是

var data = [{
value: 1,
t: 1487203500000
}, {
value: null,
t: null
} {
value: 2,
t: 1487213700000
}];

在附加时,我需要插入相同的索引,并且应重新调整现有值。

最佳答案

您可以使用array.splice()来实现

The splice() method adds/removes items to/from an array.

var data = [{
value: 1,
t: 1487203500000
}, {
value: 2,
t: 1487213700000
}];

// put your index here
// v
data.splice(1, 0, {value: null, t: null});

console.log(JSON.stringify(data, 0, 8));

在此代码中

data.splice(1, 0, {value: null, t: null});

1st Parameter (1) -> indicates the position where you want to insert.
2nd Parameter (0) -> indicates how many elements you want to remove.
3rd Parameter ({obj}) -> is the object which we want to insert at position 1.

关于javascript - 如何在 for 循环内将新项目附加到同一数组中的同一索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42431657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com