arr.push(arr.splice(n,1)) "swallows" 移动对象的属性

arr.push(arr.splice(n,1)) "swallows" the property of the moved object

比如我想把中间的元素放到最后:

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+',');
}

但是最后一个元素的属性变成了undefined,尽管元素个数不变,为什么会这样?

splice 总是 returns 一个 数组 ,即使只有一个元素被删除。如果你想 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+',');
}

splice 方法总是 returns array not object., 所以在你的代码中第 5 个元素是 array 所以它给出未定义的值., 只需替换这一行它就会工作很好

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+',');
    }

Splice总是returns数组,使用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+',');
}