實際開發中,有時須要知道對象的全部屬性,原生js提供了一個方法Object.keys()。
Object.keys(obj)返回的是一個數組,該數組的全部元素都是字符串。這些元素是來自於給定的obj可直接枚舉的屬性,這些屬性的順序與手動遍歷該對象屬性時的一致。數組
一. 傳入數組:返回索引函數
var arr = ["a", "b", "c"]; console.log(Object.keys(arr)); // console: ["0", "1", "2"]
二. 傳入對象:返回屬性名this
var obj = {'a':'123','b':'345'}; console.log(Object.keys(obj)); //['a','b'] var obj1 = { 100: "a", 2: "b", 7: "c"}; console.log(Object.keys(obj1)); // console: ["2", "7", "100"] var obj2 = Object.create( {}, { getFoo : { value : function () { return this.foo } } } ); obj2.foo = 1; console.log(Object.keys(obj2)); // console: ["foo"]
三.傳入字符串:返回索引spa
var str = 'ab1234'; console.log(Object.keys(str)); // ["0","1","2","3","4","5"]
4、構造函數:返回空數組或者屬性名prototype
function Pasta(name, age, gender) { this.name = name; this.age = age; this.gender = gender; this.toString = function () { return (this.name + ", " + this.age + ", " + this.gender); } } console.log(Object.keys(Pasta)); //console: [] var spaghetti = new Pasta("Tom", 20, "male"); console.log(Object.keys(spaghetti)); //console: ["name", "age", "gender", "toString"]
5、注意事項
在ES5裏,若是此方法的參數不是對象(而是一個原始值),那麼它會拋出 TypeError。在ES6中,非對象的參數將被強制轉換爲一個對象。code
Object.keys("foo"); // TypeError: "foo" is not an object (ES5 code) Object.keys("foo"); // ["0", "1", "2"] (ES2015 code)
6、要在原生不支持的就環境中添加兼容的Object.keys(),能夠添加如下腳本:對象
if (!Object.keys) { Object.keys = (function () { var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'), dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ], dontEnumsLength = dontEnums.length; return function (obj) { if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object'); var result = []; for (var prop in obj) { if (hasOwnProperty.call(obj, prop)) result.push(prop); } if (hasDontEnumBug) { for (var i=0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]); } } return result; } })() };