arr.push(arr.splice(n,1))“吞下”被移动对象的属性

问题描述 投票:0回答:3

例如,我想把中间元素放到最后:

let students=[
    {"name":"a","uid":"001"},
    {"name":"b","uid":"002"},
    {"name":"c","uid":"003"},
    {"name":"d","uid":"004"},
    {"name":"e","uid":"005"},
];
students.push(students.splice(students.length/2,1));
console.log(students.length);
for(let s of students){
  console.log(s.name+':'+s.uid+',');
}

但是最后一个元素的属性变得不确定,尽管元素的数量不变,为什么会发生呢?

javascript arrays javascript-objects splice array-push
3个回答
2
投票

splice总是返回一个数组,即使只删除了一个元素。如果你想push删除student,你必须先从数组中提取它,否则你将数组推送到students(而不是学生对象):

let students=[
    {"name":"a","uid":"001"},
    {"name":"b","uid":"002"},
    {"name":"c","uid":"003"},
    {"name":"d","uid":"004"},
    {"name":"e","uid":"005"},
];
const [student] = students.splice(students.length/2,1);
students.push(student);
// or
// students.push(students.splice(students.length/2,1)[0]);
console.log(students.length);
for(let s of students){
  console.log(s.name+':'+s.uid+',');
}

-1
投票

splice方法总是返回数组而不是对象。所以在你的代码中,第5个元素是数组,所以它给出了未定义的值。,只需替换这一行就可以正常工作了

students.push(...students.splice(students.length/2,1));

知道关于...的母马(休息运算符)click here

    let students=[
        {"name":"a","uid":"001"},
        {"name":"b","uid":"002"},
        {"name":"c","uid":"003"},
        {"name":"d","uid":"004"},
        {"name":"e","uid":"005"},
    ];
    students.push(...students.splice(students.length/2,1));
    console.log(students.length);
    for(let s of students){
      console.log(s.name+':'+s.uid+',');
    }

-1
投票

Splice总是返回数组,使用spread operator来获取对象。

let students=[
  {"name":"a","uid":"001"},
  {"name":"b","uid":"002"},
  {"name":"c","uid":"003"},
  {"name":"d","uid":"004"},
  {"name":"e","uid":"005"},
];

students.push(...students.splice(students.length/2,1));

for(let s of students){
  console.log(s.name+':'+s.uid+',');
}
© www.soinside.com 2019 - 2024. All rights reserved.