概述: Object.keys() 方法會返回一個由給定對象的全部可枚舉自身屬性的屬性名組成的數組,數組中屬性名的排列順序和使用for-in循環遍歷該對象時返回的順序一致(二者的主要區別是 for-in 還會遍歷出一個對象從其原型鏈上繼承到的可枚舉屬性)。es6
1、它返回的是一個對象可枚舉屬性的數組數組
var obj = {"name": 'aaa', "code": 'dddd'} console.log(Object.keys(obj)) // [name, code]
2、 它對於key爲數字或者‘1’的會進行大小排序函數
var obj = {'4': '123', '3': '345', '1': '222'} console.log(Object.keys(obj)) // ['1', '3', '4'] var obj = {4: '123',3: '345', 1: '222'} console.log(Object.keys(obj)) // ['1', '3', '4']
3、只能返回可枚舉的屬性this
var obj2 = Object.create({}, { getFoo: { value: function () { return this.foo } } }) obj2.foo = 1 console.log(obj2) // {foo: 1, getFoo: ƒ} console.log(Object.keys(obj2)) // ["foo"]
4、針對字符串 (返回字符串的索引數組)es5
var str ='abc1234' console.log(Object.keys(str)) // ["0", "1", "2", "3", "4", "5"] // 可是這個是針對es6能夠 es5則會報錯 Object.keys("foo"); // TypeError: "foo" is not an object (ES5 code) Object.keys("foo"); // ["0", "1", "2"]
5、數組prototype
var list = ['a', 'c', 'b'] console.log(Object.keys(list)) // ['0', '1', '2']
6、構造函數code
function Arr (name, age, height) { this.name = name this.age = age this.height = height this.dd = function () { console.log(0) } } console.log(Object.keys(arr)) // [] var newArr = new Arr('bxm', 18, '170') // 構造函數的名字首字母必須爲大寫字母 console.log(Object.keys(newArr)) ["name", "age", "height", "dd"]
7、兼容問題對象
運行下面的代碼能夠兼容那些沒有原生支持Object.key方法的JavaScript環境。
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; } })() };