Cherish_Now

导航

怎么判断对象obj中是否含有某个属性以及怎么删除对象中的某个属性

一:判断对象object中是否含有某个属性
1:点( . )或者方括号( [ ] )(可以根据 Obj.x !== undefined 的返回值 来判断Obj是否有x属性)

// 创建对象
let test = {name : 'dd'}
// 获取对象的自身的属性
test.name            //"dd"
test["name"]         //"dd"

// 获取不存在的属性
test.age             //undefined

// 获取原型上的属性
test["toString"]     // ƒ toString() { [native code] }

// 新增一个值为undefined的属性
test.undef = undefined

test.undef              //undefined    不能用在属性值存在,但可能为 undefined的场景

2: in 运算符

'name' in test        //true
'undef' in test             //true
'toString' in test    //true
'age' in test           //false

注意:这种方式的局限性就是无法区分自身和原型链上的属性,在只需要判断自身属性是否存在时,这种方式就不适用了。这时需要hasOwnProperty()

3:hasOwnProperty()

test.hasOwnProperty('name')        //true   自身属性
test.hasOwnProperty('age')           //false  不存在
test.hasOwnProperty('toString')    //false  原型链上属性

二:删除对象中的某个属性(delete不能删除直接使用var定义的变量)

let a={name:'dd',age: 18, arr:[1,2,3,{grade:'二年级'}]};
delete a.age;// true
console.log(a);//{name: "dd", arr: Array(4)}
delete a.arr;
console.log(a);//{name: "dd"}

posted on 2019-05-08 18:24  Cherish_Now  阅读(1179)  评论(1编辑  收藏  举报