gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:39:38 25 4
gpt4 key购买 nike

例如,假设我有数组:

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

但它并没有像我预期的那样工作。

最佳答案

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

关于javascript - 如何在不首先复制所有值的情况下移动数组中对象的属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53039689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com