下面小編就為大家帶來一篇javascript遍歷json物件的key和任意js物件屬性實例。小編覺得蠻不錯的,現在就分享給大家,也給大家做個參考。一起跟著小編過來看看吧
使用keys 方法取得該物件的屬性和方法:##
function Pasta(grain, width, shape) { this.grain = grain; this.width = width; this.shape = shape; this.toString = function () { return (this.grain + ", " + this.width + ", " + this.shape); } } var spaghetti = new Pasta("wheat", 0.2, "circle"); var arr = Object.keys(spaghetti); document.write(arr);結果圖: 顯示Pasta 物件中以字母「g」開頭的所有可枚舉屬性的名稱:
function Pasta(grain, width, shape) { this.grain = grain; this.width = width; this.shape = shape; } function CheckKey(value) { var firstChar = value.substr(0, 1); if (firstChar.toLowerCase() == "g") { return true; } else { return false; } } var polenta = new Pasta("corn", 1, "mush"); var keys = Object.keys(polenta).filter(CheckKey); document.write(keys);結果如圖: 遍歷json物件的鍵:
var an_obj = { 100: 'a', 2: 'b', 7: 'c', "name": "wu", "interesting": "Game" }; document.write(Object.keys(an_obj));結果如圖:
以上是詳解javascript遍歷json物件的key和任意js物件屬性的範例程式碼(圖)的詳細內容。更多資訊請關注PHP中文網其他相關文章!