判断对象为空的方法
1.使用 JSON.stringify()
方法
对象是引用型数据 无法直接比较
const obj = {};
const str = JSON.stringify(obj);
const isEmpty = (str === '{}');
2.使用 Object.keys()
方法
Object.keys()
静态方法返回一个由给定对象自身的可枚举的字符串键属性名组成的数组。
const obj = {};
const keys = Object.keys(obj);
const isEmpty = (keys.length === 0);
判断是数组
1.Array.isArray()
方法
const arr = [1, 2, 3];
console.log(Array.isArray(arr)); // true
2.instanceof Array
- 检查对象的原型链中是否包含
Array.prototype
。const arr = [1, 2, 3]; console.log(arr instanceof Array); // true
判断是否是字符串
1.使用 typeof
运算符
const data='123'
typeof data === "string"
2.使用 constructor
属性
- 每个JavaScript对象都有一个
constructor
属性,指向创建它的构造函数。const str = "Hello, world!"; console.log(str.constructor === String); // true
3.使用 instanceof
运算符
const str = "Hello, world!";
console.log((new String(str)) instanceof String); // true