JS中對象屬性的可枚舉性

在JS中,對象的屬性分爲可枚舉和不可枚舉,它是由屬性的enumerable值決定的,true爲可枚舉,false爲不可枚舉

JS中預定義的原型屬性一般是不可枚舉的,而自己定義的屬性一般可枚舉

可以通過propertyIsEnumerable方法判斷該屬性是否可枚舉

屬性的枚舉性會影響以下三個函數的結果:

for ... in ...

Object.keys()

JSON.stringify()

例子:

function Person(){
	this.name = 'kong';
}
Person.prototype = {
	age : 18,
	job : 'student'
}
var a = new Person();
Object.defineProperty(a, 'sex', {
	value : 'men',
	enumerable : false		//定義該屬性不可枚舉
})

//for in
for(var k in a){
	console.log(k);
}
//name age job

//Object.keys()
console.log(Object.keys(a));
//['name']

//JSON.stringify()
console.log(JSON.stringify(a));
//{'name' : 'kong'}

//propertyIsEnumerable方法判斷該屬性是否可枚舉
console.log(a.propertyIsEnumerable('name'));	//true
console.log(a.propertyIsEnumerable('age'));		//false
console.log(a.propertyIsEnumerable('sex'));		//false
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章