如何在不先复制所有值的情况下移动数组中对象的属性值?

时间:2018-10-29 06:10:40

标签: javascript arrays algorithm

例如,假设我有数组:

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

我想移动uid的值,预期结果:

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

如何在不首先将所有uid复制到新数组的情况下执行此操作?我尝试过:

let students=[
        {"name":"a","uid":"001"},
        {"name":"b","uid":"002"},
        {"name":"c","uid":"003"}
    ];
let temp=students[0].uid;
for(let i=0;i<students.length;i++){
  students[(i+1)%students.length].uid=temp;
  temp=students[i].uid;
}

for(let s of students){
  console.log(s.name+':'+s.uid+',');
}

但是它没有按我预期的那样工作。

2 个答案:

答案 0 :(得分:0)

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

let temp = students[0].uid
for(let i=0;i<students.length;i++){
  let temp2 = students[(i+1)%students.length].uid
  students[(i+1)%students.length].uid=temp;
  temp = temp2
}

for(let s of students){
  console.log(s.name+':'+s.uid+',');
}

答案 1 :(得分:0)

您几乎拥有它。您只需要复制第一个。我只提供伪代码,因为我们不在Stack Overflow中做作业:

first_uuid = students[0].uuid
for loop from students[0] to students[one before last]
     student[i].uuid = student[i+i].uuid
student[last] = first_uuid

在您的代码中,您无需弄乱模数或触摸temp