admin管理员组

文章数量:1292056

i want to use a for in oop to get the value of all the properties but do not know how. The tutorial i am following gives this example of how i can do it, but i dont understand it.

for(var x in dog) { console.log(dog[x]); }

var nyc = {
    fullName: "New York City",
    mayor: "Michael Bloomberg",
    population: 8000000,
    boroughs: 5
};

// write a for-in loop to print the value of nyc's properties

i want to use a for in oop to get the value of all the properties but do not know how. The tutorial i am following gives this example of how i can do it, but i dont understand it.

for(var x in dog) { console.log(dog[x]); }

var nyc = {
    fullName: "New York City",
    mayor: "Michael Bloomberg",
    population: 8000000,
    boroughs: 5
};

// write a for-in loop to print the value of nyc's properties
Share Improve this question edited May 18, 2024 at 23:26 nbro 15.9k34 gold badges119 silver badges214 bronze badges asked Jul 14, 2013 at 12:11 Create MeowCreate Meow 431 gold badge1 silver badge1 bronze badge 6
  • i know with this code for(var x in dog) { console.log(dog[x]); } – Create Meow Commented Jul 14, 2013 at 12:12
  • 1 What does your Javascript book say? – Lightness Races in Orbit Commented Jul 14, 2013 at 12:13
  • print the value of each property in nyc using for in loop – Create Meow Commented Jul 14, 2013 at 12:14
  • 1 It says a lot more than that. You need to learn the language. – Lightness Races in Orbit Commented Jul 14, 2013 at 12:14
  • 1 You have an example for..in that works on an object called dog. Your object is called nyc. If you copy that loop to where the "write a loop" ment is, what change do you think you need to make to it to work with your object? – nnnnnn Commented Jul 14, 2013 at 12:17
 |  Show 1 more ment

4 Answers 4

Reset to default 5

I suggest you to use variable name that has some meaning instead of x and y like:

for(var property in object){
    console.log(object[property]);
}

for your object

for(var prop in nyc){
    console.log(nyc[prop]);
}

Updated for ES6+

for(let prop in nyc){
    console.log(nyc[prop]);
}
for (var property in obj){
     console.log(property + ": " + obj[property]);
}

This should do the trick, what this does is loops through the "Properties" of the object and logs the values accordingly.

you are missing + before value.

the correct line Object.entries(obj).map(([key, value]) => key + ":" + value)

A one-liner would be:

Object.entries(obj).map(([key, value]) => key + ":" value)

本文标签: How do i print the value of all properties in an object in javascriptStack Overflow