Object.keys數組
定義:返回一個對象可枚舉屬性的字符串數組;spa
Object.getOwnPropertyNamescode
定義:返回一個對象可枚舉、不可枚舉屬性的名稱;對象
定義:可枚舉屬性是指那些內部 「可枚舉」 標誌設置爲 true 的屬性,對於經過直接的賦值和屬性初始化的屬性,該標識值默認爲即爲 true,對於經過 Object.defineProperty 等定義的屬性,該標識值默認爲 false。blog
var obj = { "prop1": "v1" }; Object.defineProperty(obj, "prop2", { value: "v2", writable: false }); console.log(Object.keys(obj).length); //output:1 console.log(Object.getOwnPropertyNames(obj).length); //output:2 console.log(Object.keys(obj)); //output:Array[1] => [0: "prop1"] console.log(Object.getOwnPropertyNames(obj)); //output:Array[2] => [0: "prop1", 1: "prop2"]
功能 | 可枚舉 | 可枚舉、不可枚舉 |
判斷 |
propertyIsEnumerable
|
in/hasOwnProperty |
訪問 | Object.keys | Object.getOwnPropertyNames |
迭代 | for..in.. | Object.getOwnPropertyNames |
var obj = { "prop1": "v1" }; Object.defineProperty(obj, "prop2", { value: "v2", writable: true }); console.log(obj.hasOwnProperty("prop1")); //output: true console.log(obj.hasOwnProperty("prop2")); //output: true console.log(obj.propertyIsEnumerable("prop1")); //output: true console.log(obj.propertyIsEnumerable("prop2")); //output: false console.log('prop1' in obj); //output: true console.log('prop2' in obj); //output: true for (var item in obj) { console.log(item); } //output:prop1 for (var item in Object.getOwnPropertyNames(obj)) { console.log(Object.getOwnPropertyNames(obj)[item]); } //ouput:[prop1,prop2]
Object.hasOwnProperty()
Object.propertyIsEnumerable()
Object.getOwnPropertyNames()
Object.keys()ip
屬性的可枚舉性和全部權 字符串