动态对象键仅采用循环的最后一个值。

huangapple go评论81阅读模式
英文:

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 &lt; 5; i++) {
  obj[&#39;arr&#39;] = [];
  obj[&#39;arr&#39;].push(i);
}

console.log(obj[&#39;arr&#39;]);

//    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 &lt; 5; i++) {
  obj[&#39;arr&#39;] ??= [];
  obj[&#39;arr&#39;].push(i);
}

console.log(obj[&#39;arr&#39;]);

<!-- 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 = { &quot;arr&quot;:[] };

for (let i = 0; i &lt; 5; i++) {
  obj[&#39;arr&#39;].push(i);
}

console.log(obj[&#39;arr&#39;]);

<!-- 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[&#39;arr&#39;] in each iteration.

Instead, do this:

const obj = {};
obj[&#39;arr&#39;] = [];

for (let i = 0; i &lt; 5; i++) {
  obj[&quot;arr&quot;].push(i);
}

console.log(obj[&quot;arr&quot;]);

huangapple
  • 本文由 发表于 2023年6月1日 17:01:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76380274.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定