来自网址(http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_state_forin)的代码返回“John Doe 25”。 如何获取“fname lname age”等属性名称?
--no-commit
答案 0 :(得分:1)
您可以使用keys
函数获取所有对象属性(也称为键!)的数组:
Object.keys(person);
所以要打印出你可以做的键/值对列表:
var person = { fname:"John", lname:"Doe", age:25 };
var personProps = Object.keys(person);
for(var i = 0; i < personProps.length; i++){
var key = personProps[i];
var value = person[key];
console.log(key + " : " + value);
}
或者您可以直接循环对象的属性,如下所示:
var person = { fname:"John", lname:"Doe", age:25 };
for (key in person) {
console.log(key + " : " + person[key]);
};
输出:
fname : John
name : Doe
age : 25
答案 1 :(得分:0)
使用Object.keys(yourObj)
获取一系列密钥。像:
function myFunction() {
var person = {
fname: "John",
lname: "Doe",
age: 25
};
var text = "";
var x;
var keys = Object.keys(person);
for (x = 0; x < keys.length; x++) {
text += keys[x] + " ";
}
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
答案 2 :(得分:0)
你看到那个循环:
for (x in person) {
text += person[name] + " ";
}
x将是人物对象的属性。
答案 3 :(得分:0)
for..in
循环已遍历对象的键。您只需将person[x]
更改为x
。
var button = document.getElementById('tryit');
var output = document.getElementById('demo');
var person = { fname: "John", lname: "Doe", age: 25 };
button.onclick = function() {
var text = "";
for (var x in person) {
text += x + " ";
}
output.innerHTML = text;
};
&#13;
<p>Click the button to loop through the properties of an object.</p>
<button id="tryit">Try it</button>
<p id="demo"></p>
&#13;
使用Object.keys
和Array.prototype.forEach
来执行相同的操作也很常见,但不会迭代对象的prototype
中的任何继承属性。
var text = "";
Object.keys(person).forEach(function(x) {
text += x + " ";
});