我认为在将对象添加或插入对象数组中在逻辑上是合理的,但我得到的结果很时髦。有人可以告诉我我在做什么错吗?当我尝试将对象插入索引为0的对象数组中时,为什么下面的代码返回空数组;当我尝试在对象数组的末尾添加对象时,为什么下面的代码返回4? >
let objArr = [{
id: 1,
company: "Rapid Precision Mfg.",
title: "Quality Engineer",
firstName: "Dongyob",
lastName: "Lee",
officePh: "",
ext: "",
cell: "669-294-0910",
email: "dyl4810@gmail.com"
},
{
id: 2,
company: "Facebook",
title: "Frontend Developer",
firstName: "Edward",
lastName: "Simmons",
officePh: "408-516-4662",
ext: "003",
cell: "669-252-4251",
email: "edwardsimmons@gmail.com"
}
]
let nobj = {
id: 1,
company: "Rapid Precision Mfg.",
title: "Quality Engineer",
firstName: "Dongyob",
lastName: "Lee",
officePh: "",
ext: "",
cell: "669-294-0910",
email: "dyl4810@gmail.com"
}
console.log(objArr.splice(0, 0, nobj)) //Outcome: []
console.log(objArr.push(nobj)) //Outcome: 4
答案 0 :(得分:3)
splice
返回数组的已删除元素。如果您没有在splice
调用中删除任何元素,则返回的数组将为空。
const arr = [0, 1, 2, 3];
// from index 0, don't remove any elements, and insert element 'foo':
console.log(arr.splice(0, 0, 'foo'));
push
返回数组的新长度。输出为4,因为数组以2个项目开始,您splice
放入一个项目(长度为3),然后push
放入另一个项目,长度为4。
您当前的代码
console.log(objArr.splice(0, 0, nobj))
console.log(objArr.push(nobj))
正在将nobj
插入到数组的最后一个位置,插入到数组的第一个位置-如果要查看之后的数组,请记录该数组:
console.log(objArr);
请注意,您可以使用splice
来代替unshift
插入索引0的元素:
const arr = [0, 1, 2, 3];
arr.unshift('foo');
console.log(arr);
答案 1 :(得分:0)
拼接语法为array.splice(index, howmany, item1, ....., itemX)
,并返回removed
。
如果要测试更改,请console.log(objArr)
let objArr = [{
id: 1,
company: "Rapid Precision Mfg.",
title: "Quality Engineer",
firstName: "Dongyob",
lastName: "Lee",
officePh: "",
ext: "",
cell: "669-294-0910",
email: "dyl4810@gmail.com"
},
{
id: 2,
company: "Facebook",
title: "Frontend Developer",
firstName: "Edward",
lastName: "Simmons",
officePh: "408-516-4662",
ext: "003",
cell: "669-252-4251",
email: "edwardsimmons@gmail.com"
}
]
let nobj = {
id: 1,
company: "Rapid Precision Mfg.",
title: "Quality Engineer",
firstName: "Dongyob",
lastName: "Lee",
officePh: "",
ext: "",
cell: "669-294-0910",
email: "dyl4810@gmail.com"
}
objArr.splice(0, 0, nobj)
console.log(objArr) //Outcome: []
//console.log(objArr.push(nobj))
答案 2 :(得分:0)
正如以上用户所提到的,splice()
返回数组中已删除的元素。如果您尝试将一个对象推到数组的开头,那么另一种方法是使用spread syntax(是ES6!)。我认为它比您尝试使用的方法更具可读性。
//[nobj, ...objArr]
console.log([nobj, ...objArr]);
与unshift()不同,它不会就地修改原始objArr
数组。
const newArray = [nobj, ...objArr];