如何使用JavaScript遍历对象数组?

时间:2018-10-10 15:09:30

标签: javascript

我试图循环包含对象的数组,但我不断出错:“无法设置未定义的属性'color'”。我在做什么错了?

var ObjectTest = function(something1, something2){
    this.Name = something1;
    this.Job = something2;
    this.color = '';
    this.numbers = [];
    
}

var first = new ObjectTest('Paul', 'teacher');
var second = new ObjectTest('Jane', 'doctor');
var third = new ObjectTest('Mike', 'student');

var someArray = [];
someArray.push(first, second, third);
console.log(someArray);


for(var i =0; i <= someArray.length; i++){
    someArray[i].color = 'red';
};

4 个答案:

答案 0 :(得分:1)

您需要迭代直到数组的长度但不能超过数组的长度,因为索引是从零开始的

ds <- data.frame(arm=c("Group 1","Group 2","Group 3", "Group 4"), 
                 Time = c("First","Second","Third"),
                 result = rnorm(n = 120,mean=10,sd=2))
ds %>% 
  group_by(arm, Time) %>% 
  summarise_at(vars(result), funs(mean, sd)) %>% 
  gather(key, val, mean:sd) %>% 
  print(n=nrow(.))

一个数组为不存在的项目返回for (var i = 0; i < someArray.length; i++) { // ^ undefined没有属性来分配新值。

undefined

答案 1 :(得分:1)

<=不对

var ObjectTest = function(something1, something2){
    this.Name = something1;
    this.Job = something2;
    this.color = '';
    this.numbers = [];
    
}

var first = new ObjectTest('Paul', 'teacher');
var second = new ObjectTest('Jane', 'doctor');
var third = new ObjectTest('Mike', 'student');

var someArray = [];
someArray.push(first, second, third);


for(var i =0; i < someArray.length; i++){
    someArray[i].color = 'red';
};
console.log(someArray);

答案 2 :(得分:0)

在循环中将var ObjectTest = function(something1, something2) { this.Name = something1; this.Job = something2; this.color = ''; this.numbers = []; }; var first = new ObjectTest('Paul', 'teacher'); var second = new ObjectTest('Jane', 'doctor'); var third = new ObjectTest('Mike', 'student'); var someArray = []; someArray.push(first, second, third); for (var i = 0; i < someArray.length; i++) { someArray[i].color = 'red'; } // no semicolon here console.log(someArray);替换为<=

数组上只有3个项目,这意味着您拥有索引<01。循环到达2时应停止。但是由于您使用的是3而不是<=,所以<i <= 3时的i3,因此执行了代码。该错误是由true不存在引起的。

一种更安全的循环遍历数组而不处理索引的方法是使用someArray[3]。它只会循环遍历数组中所有项目的次数。

array.forEach

答案 3 :(得分:0)

遍历数组的更简单方法是使用forEach。 像这样:

{ [Error: unsupported BodyInit type]
  line: 21147,
  column: 55,
  sourceURL: 'http://localhost:8081/index.delta?platform=android&dev=true&minify=false' }