Search code examples
javascriptarraysjavascript-objectssplicearray-push

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


for example,I want to put the middle element to the last:

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

but the property of last element becomes undefined, despite the number of elements unchanged, why would it happen?


Solution

  • splice always returns an array, even when only one element is being removed. If you want to push the removed student, you'll have to extract it from the array first, otherwise you're pushing an array to students (rather than a student object):

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