在 for 循环中创建新对象
我想创建一个新对象并为存储在某个 json 中的每个数组分配一些属性。我基本上都在工作,除了......
for (var i in json) {
a = 0;
a++;
a = new Object();
for (var key in json[i]) {
var Key = key;
var Value = json[i][key];
a[Key] = Value;
}
a.outputProperties();
}
当我输出对象属性时,一切都是未定义的。
如果我在循环外创建一个对象并为其分配属性,它似乎工作正常,只是第一组属性被以下内容覆盖。不知道为什么我无法在循环内动态创建对象并分配属性。
I want to create a new object and assign some properties for each array stored within some json. I have this mostly working except...
for (var i in json) {
a = 0;
a++;
a = new Object();
for (var key in json[i]) {
var Key = key;
var Value = json[i][key];
a[Key] = Value;
}
a.outputProperties();
}
When I output the object properties, everything is undefined.
If I create a single object outside the loop and assign the properties to it, it seems to work OK except that the first set of properties get overwritten with the following. Not sure why I wouldn't be able to create objects and assign properties inside the loop dynamically.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您实际上从未设置过 a 的任何属性。您只需设置
sup2
的属性。顺便说一句,你还有其他不必要的东西,比如 var Key = key; 试试这个:You never actually set any properties of
a
. You just set properties ofsup2
. On a side note you have other unnecessary stuff in there likevar Key = key;
Try this:您粘贴的代码对我来说看起来不正确,因为它似乎没有结合在一起。
这三行的作用是什么:
你似乎用there做了三件相互矛盾的事情。我的猜测是 a 应该是您未显示的某些外部事物的索引。
那么
与您之前所做的supplement() 应该是什么关系呢?
The code you pasted doesn't look right to me, in the sense of it doesn't seem to hang together.
What do these three lines do:
You seem to do three contradictory things with a there. My guess is that a's meant to be an index to some external thing you don't show.
Then what is
supposed to be, some relationship to the supplement() you made earlier?
戴夫史密斯的答案非常接近我所需要的,但它没有在循环内创建新对象。这是我更新的代码,它提供了所需的结果:
每个新对象现在都存储在一个数组 theGoods[] 中;
我现在可以通过编写如下内容来引用该对象:
theGoods["obj2"].someMethod();
Dave Smith's answer was pretty close to what I needed but it didn't create new objects within the loop. Here's my updated code that provided the desired result:
Each new object is now stored within an array, theGoods[];
I can now reference that object by writing something like:
theGoods["obj2"].someMethod();