javascript---判断对象中是否存在变量和方法的方式

93 阅读2分钟

此处写的方法均为作者实际工作中用到的一些方法,如存在错误,请大家批评指正。大家有更好的方法,可以写到评论区,大家一起学习!👍👍

Object.hasOwnProperty()

Object.prototype.hasOwnProperty.call()

关于hasOwnProperty的用法及优缺点已经在juejin.cn/post/715839… 中进行了 阐述,有兴趣的大佬们,可以移步这里进行查看。


in 运算符

in 运算符主要的两个特性

  • 判断对象里面有没有这个变量方法
  • 判断数组的下标有没有值,是不是为空

判断对象

//判断对象里面有没有这个变量和方法
let obj = {a:1,b:2};
console.log('a' in obj)  //true
console.log('toString' in obj) // true
console.log('valueOf' in obj)  // true

let obj1 = Object.create(null);
console.log('a' in obj1)  //false,不会报错
console.log('toString' in obj1) //false,不会报错 

🚁看到这里大家有没有发现in 运算符hasOwnProperty()的区别呢?

🏀 in运算符会遍历原型链上的方法和变量;hasOwnProperty不会遍历原型链上的方法和变量。

判断数组

//判断数组的下标有没有值,是不是为空
let arr = [1,2,3];
console.log(1 in arr) //true,其中1为arr下标,值对象的2
console.log(3 in arr) //false,不存在下标为3的值

let arr1 = [1,,2,3];
console.log(1 in arr1) //false,下标为1的为空

in右操作数必须是一个对象值。

这里要注意new Boolean()/new String()等

//new String() 对象
let color1 = new String('test');
console.log('length' in color1) //true
console.log('trim' in color1)  //true

//右操作数必须是一个对象值。
let color2 = 'test1';
console.log('length' in color2)  //报错

删除属性或方法

//数组
let a = [1,2,2,3,4];
delete a[1];
console.log(1 in a); //false
//对象
let b = {a:1,b:2,c:3};
delete a.b;
console.log('b' in b) //false

属性赋值undefined或null

//数组
let a = [1,2,2,3,4];
a[1] = null;
console.log(1 in a); //true
a[2] = undefined;
console.log(2 in a) //true
//对象
let b = {a:1,b:3,c:4};
a.a = null;
console.log('a' in b) // true
a.b = undefined;
console.log('b' in b)  // true

ES6 Reflect has()方法

Reflect.has(obj,name) es6.ruanyifeng.com/#docs/refle…

Reflect.has方法对应name in obj里面的in运算符。

var myObject = {
  foo: 1,
};

// 旧写法
'foo' in myObject // true

// 新写法
Reflect.has(myObject, 'foo') // true

如果Reflect.has()方法的第一个参数不是对象,会报错。


补充方法:
Object.keys().includes()