打印 Javascript 对象中的所有属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17627916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:00:49  来源:igfitidea点击:

Printing all properties in a Javascript Object

javascript

提问by Rtr Rtr

I am following a code academy tutorial and i am finding this difficult.

我正在学习代码学院教程,我发现这很难。

The assignment is the following:

任务如下:

Use a for-in loop to print out all the properties of nyc.

使用 for-in 循环打印出 nyc 的所有属性。

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

// write your for-in loop here
for (var  in nyc){
    console.log(population);
}

回答by lostsource

Your syntax is incorrect. The varkeyword in your forloop must be followed by a variable name, in this case its propName

你的语法不正确。循环中的var关键字for必须后跟变量名,在本例中为propName

var propValue;
for(var propName in nyc) {
    propValue = nyc[propName]

    console.log(propName,propValue);
}

I suggest you have a look here for some basics:

我建议你看看这里的一些基础知识:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

回答by Tomas Nekvinda

What about this:

那这个呢:

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

for (var x in nyc){
    txt += nyc[x];
}