gpt4 book ai didi

javascript - 如何在数组元素中添加数组

转载 作者:行者123 更新时间:2023-11-29 20:49:27 25 4
gpt4 key购买 nike

我有这样的 _assignedTripData 数组元素。

0: {id: 100959872, cityCode: "PHX", airportID: "PHX", local: 0, guestID: 0, …}
1: {id: 100952759, cityCode: "PHX", airportID: "PHX", local: 0, guestID: 0, …}
2: {id: 100952761, cityCode: "PHX", airportID: "PHX", local: 0, guestID: 0, …}
3: {id: 100952766, cityCode: "PHX", airportID: "PHX", local: 0, guestID: 0, …}

但是当我使用 _assignedTripData.splice(0,1) 在 0 位置拼接元素并存储到 var newArray = new Array();之后我想使用 _assignedTripData.splice(0,0,newArray) 在相同位置插入相同记录,最终输出将变为

只看到数组的 0 索引是对象,为什么?

0: [{…}]
1: {id: 100952759, cityCode: "PHX", airportID: "PHX", local: 0, guestID: 0, …}
2: {id: 100952761, cityCode: "PHX", airportID: "PHX", local: 0, guestID: 0, …}
3: {id: 100952766, cityCode: "PHX", airportID: "PHX", local: 0, guestID: 0, …}

在第一个记录未定义显示时,当我将 _assignedTripData 数据绑定(bind)到 tboday 时,在 0 位置添加了数组对象。

我的问题是如何删除“x”位置的数组并将它们添加到相同的位置,以便数组对象结构不会改变。回复任何建议。我是 Jquery 的新手。

最佳答案

来自 docs , Array.splice 返回

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

因此,您需要使用 Spread Syntax达到预期的效果。

let arr = [1,2];
let v = arr.splice(0,1);
arr.splice(0,0, ...v);
console.log(arr);

关于javascript - 如何在数组元素中添加数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52640538/

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