以前在js-object这个分类里面也写过keys相关的api
在JavaScript1.8.5中,加入了原生的Object.keys这个api
Object.keys(obj);
/*简单举例*/
Object.keys({"A":"a","B":"b"}); //["A","B"]
兼容性写法:
if(!Object.keys){
Object.keys = (function(){
var hasOwnPrototype = Object.prototype.hasOwnPrototype,
hasDontEnumBug = !({toString:null}).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocalString',
'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;
}
})
}
浏览器支持情况:
标签:obj,keys,Object,prop,toString,var,JavaScript1.8 From: https://blog.51cto.com/u_16170312/6551651