javascript属性操作

时间:2021-07-31 23:06:18

属性的读写


//属性添加
var obj = {x:1,y:2}; obj.z = 3; obj["m"] = 4;
//属性的读取
var obj = {x: 1, y: 2, z: 3, m: 4}; for(p in obj){
console.info(p);
}

属性的删除


var person = {age:45,name:"tom"};

person.age  //

delete person.age   //true

person.age  //undefined

属性标签【configurable】

var obj = {age:1,name:"cat"};

Object.getOwnPropertyDescriptor(obj,'age');    

//Object {value: 1, writable: true, enumerable: true, configurable: true};
//getOwnPropertyDescriptor()方法--查看age的属性标签 Object.defineProperty(obj,'age',{configurable:false}); //设置age属性configurable标签为false【表示age属性不可配置】 Object.getOwnPropertyDescriptor(obj,'age');
Object {value: 1, writable: true, enumerable: true, configurable: false}; delete obj.age //false obj.age //

不能删除的特殊情况


1 var定义的全局变量与局部变量

var globalValue = 90;

delete globalValue  //false

(function(){
var localValue = 90;
return delete localValue;
})(); //false //隐式的创建全局变量是可以删除的
yinshi = 90;

delete yinshi  //true

2 全局定义函数与局部定义的函数

function test(){}
delete test; //false (function(){
function localfunction(){};
return delete localfunction; //false
})();

判断属性是否存在


var dog = {};

dog.name = "dong";

dog.age = 89;

"name" in dog;  //true

"abc" in dog  //false

"toString" in  dog //true    //in操作符 会查找原型链。

dog.hasOwnProperty('name');  //true

dog.hasOwnProperty('toString');  //false   不查找原型链用hasOwnProperty方法

属性的枚举


var o = {x:1,y:2,z:3}

for(key in o){
console.info(key) //x y z
} Object.keys(o) //["x", "y", "z"]

【Enumerable】属性标签


var o = {x:1,y:2,z:3}

//propertyIsEnumerable 检测属性的【Enumerable】为true or false

o.propertyIsEnumerable('x')  //true

o.propertyIsEnumerable('y')  //true

o.propertyIsEnumerable('z')  //true

o.propertyIsEnumerable('toString') //false

//只有propertyIsEnumerable为true的属性,可以枚举
for(key in o){
console.info(key) //x y z
}
var o = {x:1,y:2,z:3}

//设置对象的x属性【enumerable】标签为false

Object.defineProperty(o,'x',{enumerable:false})

o.propertyIsEnumerable('x')  //false

for(key in o){
console.info(key) //y z
}