[英]How to loop over an array of objects using 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'; };
您需要迭代直到数组的长度,但不能超过,因为索引是从零开始的
for (var i = 0; i < someArray.length; i++) {
// ^
对于不存在的项目,数组返回undefined
。 undefined
没有属性可分配新值。
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);
<=
是荣
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);
在循环中将<=
替换为<
。
这里只有3个项目的阵列上,这意味着你已经索引0
, 1
和2
。 循环应在到达3
时停止。 但是由于您使用了<=
而不是<
,所以当i
为3
时, i <= 3
3
为true
因此可以执行代码。 该错误是由someArray[3]
不存在引起的。
在数组中循环而不处理索引的一种更安全的方法是使用array.forEach
。 它只会循环执行数组中存在的项的次数。
someArray.forEach((object, index) => {
object.color = 'red'
})
遍历数组的一种更简单的方法是使用forEach。 像这样:
someArray.forEach(data => data.color = 'red');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.