原生js提供了一个方法Object.keys()。
Object.keys(obj)返回的是一个数组,该数组的所有元素都是字符串。这些元素是来自于给定的obj可直接枚举的属性,这些属性的顺序与手动遍历该对象属性时的一致。
一. 传入数组:返回索引
var arr = [“a”, “b”, “c”];
console.log(Object.keys(arr)); // console: [“0”, “1”, “2”]
二. 传入对象:返回属性名
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”]
三.传入字符串:返回索引
var str = ‘ab1234’;
console.log(Object.keys(str)); // [“0”,“1”,“2”,“3”,“4”,“5”]
四、构造函数:返回空数组或者属性名
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"]
五、注意事项
在ES5里,如果此方法的参数不是对象(而是一个原始值),那么它会抛出 TypeError。在ES6中,非对象的参数将被强制转换为一个对象。
Object.keys(“foo”);
// TypeError: “foo” is not an object (ES5 code)
Object.keys(“foo”);
// [“0”, “1”, “2”] (ES2015 code)
六、要在原生不支持的就环境中添加兼容的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);
}