gpt4 book ai didi

Javascript:数组中的所有对象都具有相同的属性

转载 作者:行者123 更新时间:2023-11-30 05:51:15 25 4
gpt4 key购买 nike

我正在尝试创建一个列在数组中的对象列表。 newConstant 是一个创建对象并将它们推送到数组的函数。但是,当 while 循环遍历数组并抛出包含每个数组的一个属性的警报时,它会吐出数组中每个对象的最后一个对象的值。在这种情况下,它每次都会提示“3”,但它应该提示“1”,然后是“3”,因为它们是数组“a”中两个对象的属性 x 的值。代码如下。我该如何解决这个问题?

var i = 0;
var a = [];
var newConstant = function (x, y) {
this.x = x;
this.y = y;
a.push(this);
};
var one = newConstant(1, 2);
var two = newConstant(3, 4);

while (i < a.length) {
alert(a[i].x);
i++;
}

最佳答案

您将 newConstructor 编写为构造函数,但您将其用作普通函数,请尝试添加 new 关键字。

var i = 0;
var a = [];
var newConstant = function (x, y) {
this.x = x;
this.y = y;
a.push(this);
};
var one = new newConstant(1, 2); //notice the new keyword indicating a constructor
var two = new newConstant(3, 4);

while (i < a.length) {
alert(a[i].x);
i++;
}

它正在运行:http://jsfiddle.net/V3zwW/

这是一篇关于 the this keyword in javascript 的文章.这是另一个 reference on how to correctly use the Constructor pattern

之前发生的事情是您的第二个调用将 this.x 设置为 3 但是 this 引用了 window ,这是因为函数在除非他们是构造函数,否则javascript将其分配给他们的调用者。在你的情况下,你警告 window.x (你设置为 3)两次导致 3 3

关于Javascript:数组中的所有对象都具有相同的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14741011/

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