Object.keys()枚举自身属性的属性名,返回一个值为字符串类型的数组
注意:排列顺序和使用for in循环遍历属性名的顺序一致,区别是for in会遍历出对象从原型链上继承到的可枚举属性
//数组 var arr = [1,2,3,4]; console.log(Object.keys(arr)); //['0','1','2','3'] //类数组对象 var arr1 = {'name':'Jack','age':'17','sex':'man'}; console.log(Object.keys(arr1)); //['name','age','sex'] //排序 console.log(Object.keys(arr1).sort()); //['age','name','sex']如果你想获取到一个对象上的所有属性,包括不可枚举的,可以使用Object.getOwnPropertyNames()代替Object.keys()
//数组 var arr = [1,2,3,4]; console.log(Object.getOwnPropertyNames(arr)); //['0','1','2','3','length'] //类数组对象 var arr1 = {'name':'Jack','age':'17','sex':'man'}; console.log(Object.getOwnPropertyNames(arr1)); //['name','age','sex']参考: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/keys