[英]Javascript, pushing object in for loop result in duplicated value
I have a problem to push objects inside another object inside a for loop.我在 for 循环内将对象推入另一个 object 时遇到问题。 It result in having duplicated value.
它导致具有重复值。 I assume the problem is about
references
:我认为问题与
references
有关:
var controllers = ["Patrick","Alain"];
var steval = {"name":null,"prix":{max: 5, min: 3},"comments":null};
var evals = [];
for (index = 0; index < controllers.length; ++index) {
var name = controllers[index];
var eval = steval;
eval.name = name;
console.log(eval);
evals.push(eval);
}
console.log(evals);
$("#json").html(JSON.stringify(evals));
The result is the following:结果如下:
[{"name":"Alain","prix":{"max":5,"min":3},"comments":null},{"name":"Alain","prix":{"max":5,"min":3},"comments":null}]
What I don't understand is that my console.log(eval)
return the correct value but apparently evals.push(eval)
always push the same value.我不明白的是我的
console.log(eval)
返回正确的值,但显然evals.push(eval)
总是推送相同的值。
always push the same value
总是推送相同的值
Because there is only a single object in your code: steval
.因为您的代码中只有一个 object:
steval
。 All you do is change the name
property of that one object.您所做的就是更改该 object 的
name
属性。
If you want to create multiple objects then create the object inside the loop:如果要创建多个对象,请在循环内创建 object:
var controllers = ["Patrick","Alain"]; var evals = []; for (index = 0; index < controllers.length; ++index) { var name = controllers[index]; var eval = {"name": name,"prix":{max: 5, min: 3},"comments":null}; evals.push(eval); } console.log(evals);
Slight more compact:稍微紧凑一点:
var controllers = ["Patrick","Alain"]; var evals = controllers.map(name => { return {"name": name,"prix":{max: 5, min: 3},"comments":null}; }); console.log(evals);
As noted in the other answer (credit due), there's only one instance of steval
which gets changed and pushed.正如在另一个答案(信用到期)中指出的那样,只有一个
steval
实例被更改和推送。
You can "clone" steval using jquery's $.extend
(as tagged jquery) with deep
set to true (as you have nested objects):您可以使用 jquery 的
$.extend
(作为标记的 jquery)“克隆”steval,并将deep
设置为 true(因为您有嵌套对象):
let eval = $.extend(true, {}, steval);
Alternatively, you could JSON stringify/parse to make a clone (or store the original as JSON to skip the stringify part) - but it's not ideal.或者,您可以 JSON 字符串化/解析以进行克隆(或将原始文件存储为 JSON 以跳过字符串化部分)-但这并不理想。
var controllers = ["Patrick","Alain"]; var steval = {"name":null,"prix":{max: 5, min: 3},"comments":null}; var evals = []; for (index = 0; index < controllers.length; index++) { var name = controllers[index]; let eval = $.extend(true, {}, steval); eval.name = name; console.log(eval); evals.push(eval); } console.log(evals); //console.log(JSON.stringify(evals));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.