【问题标题】:arr.push(arr.splice(n,1)) "swallows" the property of the moved objectarr.push(arr.splice(n,1)) “吞噬”移动对象的属性
【发布时间】:2018-10-29 06:25:41
【问题描述】:

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

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,尽管元素个数没有变化,为什么会这样呢?

【问题讨论】:

    标签: javascript arrays javascript-objects splice array-push


    【解决方案1】:

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

    【讨论】:

    • 这是一个很好的解释,splice 总是返回一个数组。 //students.push(students.splice(students.length/2,1)); [0] 获取数组中的元素 //students.push(students.splice(students.length/2,1)[0]);更多的人应该投票赞成这个答案。
    【解决方案2】:

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

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

    了解 ... (Rest Operator) 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+',');
        }

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 您能解释一下您在代码中所做的更改以及为什么它可以解决问题吗?
      • 拼接返回一个数组,所以使用扩展运算符深入一层。
      • 酷。编辑答案并将解释放在那里。答案不应该只是代码转储,还应该解释问题和答案。
      • 非常感谢您的反馈。对此,我真的非常感激。 :)
      猜你喜欢
      • 1970-01-01
      • 2012-04-10
      • 2019-02-24
      • 1970-01-01
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      • 2018-05-18
      • 2016-04-23
      相关资源
      最近更新 更多