Is there any way to do a for...in key values instanced object instead forEach
? With forEach
is easy for me but I'm looking for to do it with for...in.
I made this with for each:
function Person(fullName, gender, city) {
this.fullName = fullName;
this.gender = gender;
this.city = city;
}
var person01 = new Person("Nancy", "Female", "Los Angeles");
var person02 = new Person("James", "Male", "New York");
var person03 = new Person("Lucia", "Female", "Santa Barbara");
//To do the loop
var persons = [
{fullName: "Nancy", gender: "Female", city: "Los Angeles"},
{fullName: "James", gender: "Male", city: "New York"},
{fullName: "Lucia", gender: "Female", city: "Santa Barbara"},
]
function listNames(myObject) {
persons.forEach(function(obj) {
console.log(obj.fullName);
});
}
listNames(persons);
//Nancy, James, Lucia
This way works, but I need to understand how its works the for in.
Try the following:
for(var key in myObject){
console.log(myObject[key].fullName);
}
Working Example:
function Person(fullName, gender, city) { this.fullName = fullName; this.gender = gender; this.city = city; } var person01 = new Person("Nancy", "Female", "Los Angeles"); var person02 = new Person("James", "Male", "New York"); var person03 = new Person("Lucia", "Female", "Santa Barbara"); //To do the loop var persons = [ {fullName: "Nancy", gender: "Female", city: "Los Angeles"}, {fullName: "James", gender: "Male", city: "New York"}, {fullName: "Lucia", gender: "Female", city: "Santa Barbara"}, ] function listNames(myObject) { for(var key in myObject){ console.log(myObject[key].fullName); } } listNames(persons);
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.