簡體   English   中英

如何在javascript中獲取對象屬性的名稱

[英]How to get the names of an object's properties in javascript

以下來自 URL ( http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_state_forin ) 的代碼返回“John Doe 25”。 如何獲取諸如“fname lname age”之類的屬性名稱?

<!DOCTYPE html>
<html>
   <body>
      <p>Click the button to loop through the properties of an object.</p>
      <button onclick="myFunction()">Try it</button>
      <p id="demo"></p>
      <script>
         function myFunction() {
             var person = {fname:"John", lname:"Doe", age:25}; 

             var text = "";
             var x;
             for (x in person) {
                 text += person[name] + " ";
             }
             document.getElementById("demo").innerHTML = text;
         }
      </script>
   </body>
</html>

您可以使用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

使用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>

你看到那個循環:

for (x in person) {
    text += person[name] + " ";
}

x 將是 person 對象的屬性。

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; };
 <p>Click the button to loop through the properties of an object.</p> <button id="tryit">Try it</button> <p id="demo"></p>

使用Object.keysArray.prototype.forEach來做同樣的事情也是很常見的,但不迭代對象prototype的任何繼承屬性。

var text = "";
Object.keys(person).forEach(function(x) {
    text += x + " ";
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM