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 calleddog
. Your object is callednyc
. 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
4 Answers
Reset to default 5I 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
版权声明:本文标题:How do i print the value of all properties in an object in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741546460a2384624.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论