一般采用 for...in
循环即可取出键值。
var obj = {
name : 'zhangsan',
age : 18,
sex : 'man'
}
var arr = [];
for(var i in obj){
arr.push(i);
}
console.log(arr);//["name", "age", "sex"]
若使用 prototype
后面追加的属性。不希望获取到,可以使用hasOwnProperty。
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sex = 'woman';
var obj = new Person('lisi',20);
var arr1 = [],arr2 = [];
for(var i in obj){
arr1.push(i);
if(obj.hasOwnProperty(i))
arr2.push(i);
}
console.log(arr1);//["name", "age", "sex"]
console.log(arr2);//["name", "age"]
或者直接使用:
console.log(Object.keys(obj))//["name", "age"]