简体   繁体   English

在 for 循环中设置数组内对象的值

[英]Set value of an object inside an array in a for loop

I want to define an object inside an array inside a for loop:我想在 for 循环内的数组中定义一个对象:

var test = [{}];

for(j = 0; j < 10; j++){ test[j]['name'] = "Jonh Lennon"; };

console.log(test[0]['name']);

When i try to do this, i get the error "cannot set property 'name' of undefined".当我尝试这样做时,出现错误“无法设置未定义的属性‘名称’”。

 var test = []; for(j = 0; j < 10; j++){ test[j] = []; test[j]['name'] = "Jonh Lennon"; }; console.log(test[0]['name']);

Only test[0] is defined as an object literal in your code.只有 test[0] 被定义为代码中的对象字面量。 So as your loop increments past 0, test[j](where j is between 1 and 9 inclusive) will return undefined.因此,当您的循环增量超过 0 时,test[j](其中 j 介于 1 和 9 之间)将返回未定义。

Here's a quick fix that will have return an array of object literals with a key value pair of {'name':'Jonh Lennon'}.这是一个快速修复,它将返回一个带有 {'name':'Jonh Lennon'} 键值对的对象文字数组。

var test = [{}];

for(j = 0; j < 10; j++){ 
 test[j] = {};
 test[j]['name'] = "Jonh Lennon";   
};

console.log(test); // Log all john lennons

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM