JS 判断是否为对象或数组的几种方法

一.判断值是否是对象

1.toString 方式【常用】

Object.prototype.toString.call(val) === '[object Object]' // true 代表为对象

注意:这里要使用 call 方法改变作用域

2.constructor 方式

val?.constructor === Object // true 代表为对象

这里使用了 null 传导符(?.) 以防止出错

3.typeof 与 instanceof

typeof 与 instanceof 并不能完全判断一个值为对象

typeof 的取值有:

  • "undefined"——如果这个值未定义;
  • "boolean"——如果这个值是布尔值;
  • "string"——如果这个值是字符串;
  • "number"——如果这个值是数值;
  • "object"——如果这个值是对象(包括数组)或null
  • "function"——如果这个值是函数;
  • "symbol"——如果这个值是Symbol

instanceof 操作符对于数组和对象都返回 true

[] instanceof Object // true
new Object instanceof Object // true

4.__proto__ 方式【不推荐】

 __proto__属性,用来读取或设置当前对象的 prototype 对象,此属性未纳入标准,不建议使用。

val.__proto__ === Object.prototype // true 代表为对象

5.Object.getPrototypeOf 方式

Object.getPrototypeOf(),用来读取对象的 prototype 对象。

Object.getPrototypeOf(val) === Object.prototype // true 代表为对象

二.判断值是否为数组

1.toString 方式

Object.prototype.toString.call(val) === '[object Array]' // true 代表为数组

注意:这里要用 Object 的 toString 方法,Array 的 toString 返回的是拼接的字符串

var colors = ['red', 'blue', 'green'];
console.log(colors.toString());  // red,blue,green

2.Array.isArray 方法【推荐】

ES5中提供了 isArray 方法用来判断值是否为数组

Array.isArray(val) // true 代表为数组

3.instanceof 方式

val instanceof Array // true 代表为数组

为什么 instanceof 可以用来判断数组而不可以判断对象呢?因为数组本身就是一个类似于列表的高阶对象。

4.constructor 方式

val?.constructor === Array // true 代表为数组

5. __proto__ 方式【不推荐】

val.__proto__ === Array.prototype // true 代表为数组

6.Object.getPrototypeOf 方式 

Object.getPrototypeOf(val) === Array.prototype // true 代表为数组

7.isPrototypeOf 方式

isPrototypeOf() 方法用于测试一个对象是否存在于另一个对象的原型链上。

Array.prototype.isPrototypeOf(val) // true 代表为数组

该方式不能用来判断对象!

猜你喜欢

转载自blog.csdn.net/qq_39025670/article/details/110233270