英文:
Dynamic object key is taking only last value from for loop
问题
我已经在一个空对象中初始化了一个对象,在其中我正在动态创建一个键并在for循环中插入值。但问题在于它只接受最后一个值。
为什么会这样发生,我需要在这里进行任何更正。
const obj = {};
for (let i = 0; i < 5; i++) {
obj['arr'] = [];
obj['arr'].push(i);
}
console.log(obj['arr']);
// 输出 = [4]
英文:
I have initialized an empty object in which I am dynamically creating a key and inserting values into it inside for loop.But here issue is its only taking the last value.
Why is it happening so, any correction do I need here.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const obj = {};
for (let i = 0; i < 5; i++) {
obj['arr'] = [];
obj['arr'].push(i);
}
console.log(obj['arr']);
// OUTPUT = [4]
<!-- end snippet -->
答案1
得分: 2
如前所述,每次都会创建一个新数组,因此只保存了最后一次推送。
您可以使用 ??=
Nullish_coalescing_assignment 来轻松解决这个问题,如果数组不存在则会分配一个新数组。
const obj = {};
for (let i = 0; i < 5; i++) {
obj['arr'] ??= [];
obj['arr'].push(i);
}
console.log(obj['arr']);
当然,这只在更复杂的对象循环中才有趣,但非常有用。
如果您有一个简单的循环,那么可以这样做:
const obj = { "arr": [] };
for (let i = 0; i < 5; i++) {
obj['arr'].push(i);
}
console.log(obj['arr']);
英文:
As already said, you are creating a new array each time so only the last push is saved.
You can fix this very easily with the nice ??=
Nullish_coalescing_assignment which will assign a new array if one does not already exists
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const obj = {};
for (let i = 0; i < 5; i++) {
obj['arr'] ??= [];
obj['arr'].push(i);
}
console.log(obj['arr']);
<!-- end snippet -->
It is of course only interesting in more complex object loops but very useful.
If you have a simple loop then
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const obj = { "arr":[] };
for (let i = 0; i < 5; i++) {
obj['arr'].push(i);
}
console.log(obj['arr']);
<!-- end snippet -->
答案2
得分: 0
正如 @mamun 所提到的,你在每次迭代中重新分配 obj['arr']
。
相反,做这样:
const obj = {};
obj['arr'] = [];
for (let i = 0; i < 5; i++) {
obj["arr"].push(i);
}
console.log(obj["arr"]);
英文:
As @mamun mentioned, you are reassigning obj['arr']
in each iteration.
Instead, do this:
const obj = {};
obj['arr'] = [];
for (let i = 0; i < 5; i++) {
obj["arr"].push(i);
}
console.log(obj["arr"]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论