英文:
Why for loop returning last value alone instead of all other values in javascript
问题
以下是代码的翻译部分:
我有一个下面的函数,
function test(){
const obj = {}
const arr = []
for(let i = 0; i < 100; i++) {
obj.i = i
arr.push(obj)
}
return arr
}
const res = test();
console.log(res);
这段代码返回了以下结果:
[{"i":99},{"i":99},{"i":99},...,{"i":99}]
但为什么它没有返回以下结果:
[{"i":0},{"i":1},...,{"i":99}]
有什么原因。
英文:
I have function something below,
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function test(){
const obj = {}
const arr = []
for(let i = 0; i < 100; i++) {
obj.i = i
arr.push(obj)
}
return arr
}
const res = test();
console.log(res);
<!-- end snippet -->
which returns
[{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99},{"i":99}]
but why it not return
[{"i":0},{"i":1},...,{"i":99}]
any reason.
答案1
得分: 2
你每次循环时都在替换该值。请像这样操作:
function test(){
const arr = []
for(let i = 0; i < 100; i++) {
const obj = {}
obj.i = i
arr.push(obj)
}
return arr
}
const res = test();
console.log(res);
英文:
You are replacing the value each time it is looping.Do like this
function test(){
const arr = []
for(let i = 0; i < 100; i++) {
const obj = {}
obj.i = i
arr.push(obj)
}
return arr
}
const res = test();
console.log(res);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论