Stack overflow has this example of looping trought js array of objects…
var person = [];
person[0] = {
firstName : "John",
lastName : "Doe",
age : 60
};
var i, item;
for (i = 0; i < person.length; i++) {
for (item in person[i]) {
document.write(item + ": " + person[i][item] + "<br>");
}
}
Which prints each property of object, How would I extract (print) only “age” property?
Hi there, I believe you would do it in the following way:
var person = [];
person[0] = {
firstName : "John",
lastName : "Doe",
age : 60
};
var i, item;
for (i = 0; i < person.length; i++) {
document.write("age: " + person[i].age + "<br>");
}
I am having a problem where I am looping trought array of persons…something like this…
for (var i = 0 ; i < persons.length; i++){
//do something
console.log (print each object with its properties) // this outputs each object with its properties no problem
someOtherObject.addListener('click' function(){
console.log (here it prints properties of the last object in the loop) //Where are other objects
});
}//end of for loop
What am I doing wrong here?
EDIT: I do have “click” trigger just mistyped here. I adjusted pseudo code above
So what’s happening here is that you are keeping the variable ‘td’ in scope for the event listener function. There is only 1 instance of ‘td’, and that is getting updated each time the for loop iterates. Thus, when the for loop finished, the value of td is now set to the element ‘#td7’ and your event handler is simply logging the current value of td.
In the example above, you could simply log ‘this’
var td;
for (var t=1;t<8;t++){
td = document.getElementById('td'+t);
if (typeof window.addEventListener==='function'){
td.addEventListener('click',function(){
console.log(this);
});
}
}