简体   繁体   中英

How to loop over an array of objects using javascript?

I'm trying to loop an array that contains objects and I keep getting and error: "Cannot set property 'color' of undefined". What am I doing wrong?

 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'; }; 

You need to iterate until the length of the array but not over, because indices are zero based

for (var i = 0; i < someArray.length; i++) {
//                ^

An array returns undefined for a not existing item. undefined has no property to assign a new value.

 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); 

<= was rong

 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); 

Replace <= to < in your loop.

There's only 3 items on the array, meaning you have indexes 0 , 1 and 2 . The loop should stop when it arrives at at 3 . But since you used <= and not < , i <= 3 when i is 3 is true thus executing the code. The error is caused by someArray[3] not existing.

A safer way to loop through arrays without dealing with indexes is to use array.forEach . It only loops as many times as there are items in the array.

someArray.forEach((object, index) => {
  object.color = 'red'
})

An easier way to go over an array is to use the forEach. Something like this:

someArray.forEach(data =>  data.color = 'red');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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