使用 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對象屬性實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。
新聞熱點
疑難解答