目录
三、Object.keys()、Object.getOwnPropertyNames()、for...in...对比
1、获取用 Object.create() 创建的对象的属性
前言
在JavaScript中,对象的属性分为可枚举和不可枚举之分,它们是由属性的enumerable值决定的,默认是true。可枚举性决定了这个属性能否被for…in查找遍历到。
- 可枚举属性:原型链上的枚举属性。enumerable的值,为true就是可枚举的。
- 不可枚举属性:自身定义的属性,而不是其原型链上的枚举属性。enumerable的值,为false就是不可枚举的。
一、获取对象内属性的个数
var getObjectAtrrCount = function(obj){
let count = 0;
if(Object.getOwnPropertyNames){
count = Object.getOwnPropertyNames(obj).length;
} else {// 兼容IE
for(let item in obj){
count ++;
}
}
return count;
}
二、获取对象内的属性和方法
var getObjectAtrrs = function(obj){
let arr = [];
if(Object.getOwnPropertyNames){
arr = Object.getOwnPropertyNames(obj);
} else {// 兼容IE
for(let item in obj){
arr.push(item);
}
}
return arr;
}
三、Object.keys()、Object.getOwnPropertyNames()、for...in...对比
1、获取用 Object.create() 创建的对象的属性
// 创建一个对象
var nonenum = Object.create({}, {
getFoo: {
value: function () {
return this.foo;
},
enumerable: false
}
});
nonenum.foo = 1;
nonenum.asj = 2;
Object.prototype.sayHello = function(){
return "hello";
}
// 获取对象可枚举或不可枚举的属性
console.log(Object.getOwnPropertyNames(nonenum)); // ["getFoo", "foo", "asj"]
// 获取对象可枚举的属性
console.log(Object.keys(nonenum)); // ["foo", "asj"]
// 返回直接定义在该对象上的可枚举属性或不可枚举的属性
var arr = [];
for (var item in nonenum) {
arr.push(item);
}
console.log(arr); // ["foo", "asj", "sayHello"]
// 返回直接定义在该对象上的可枚举属性
var arr = [];
for (var item in nonenum) {
if(Object.hasOwnProperty.call(nonenum, item)){
arr.push(item);
}
}
console.log(arr); // ["foo", "asj"]
2、获取通过构造函数 new 出来的对象的属性
function MyObj(name, attr) {
this.name = name;
this.sayHi = function () {
return 'hi boy';
}
}
var nonenum = new MyObj();
nonenum.foo = 1;
Object.prototype.sayHello = function () {
return "hello";
}
// 获取对象可枚举或不可枚举的属性
console.log(Object.getOwnPropertyNames(nonenum)); // ["name", "sayHi", "foo"]
// 获取对象可枚举的属性
console.log(Object.keys(nonenum)); // ["name", "sayHi", "foo"]
// 返回直接定义在该对象上的可枚举属性或不可枚举的属性
var arr = [];
for (var item in nonenum) {
arr.push(item);
}
console.log(arr); // ["name", "sayHi", "foo", "sayHello"]
// 返回直接定义在该对象上的可枚举属性
var arr = [];
for (var item in nonenum) {
if(Object.hasOwnProperty.call(nonenum, item)){
arr.push(item);
}
}
console.log(arr); // ["name", "sayHi", "foo"]
3、获取通过字面量创建的对象的属性
var nonenum = {};
Object.prototype.sayHello = function(){
return "hello";
}
nonenum.foo = 1;
nonenum.asj = 2;
// 获取对象可枚举或不可枚举的属性
console.log(Object.getOwnPropertyNames(nonenum)); // ["foo", "asj"]
// 获取对象可枚举的属性
console.log(Object.keys(nonenum)); // ["foo", "asj"]
// 返回直接定义在该对象上的可枚举属性或不可枚举的属性
var arr = [];
for (var item in nonenum) {
arr.push(item);
}
console.log(arr); // ["foo", "asj", "sayHello"]
// 返回直接定义在该对象上的可枚举属性
var arr = [];
for (var item in nonenum) {
if(Object.hasOwnProperty.call(nonenum, item)){
arr.push(item);
}
}
console.log(arr); // ["foo", "asj"]