在 Javascript 中判断一个变量是否为对象 ,你可能在网上看到过很多方法,其他在实际应用中很多都用不到,那么多方法华而不实。

本文将介绍实用又简单的 Javascript 如何判断一个变量是对象的方法。

本文将介绍如下几种在 JS 中判断一个变量是否为对象的方法:

  • js 基于 typeof 自定义函数判断一个变量是否为对象
  • js 使用 instanceof 判断一个变量是否为对象

推荐:基于 typeof 自定义函数判断变量是对象

推荐使用该方法,因为很多第三方的 Javascript 库也是使用该方法判断一个变量是否为对象。

1、自定义函数只判断对象时 Object 类型:

function isObject(value) {
  return value != null && typeof value == 'object';
}

示例代码:

function isObject(value) {
  return value != null && typeof value == 'object';
}

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
const auto = new Car('HongQi', 'H6', 2020);

console.log(isObject(auto));
// 输出为: true

2、在 JS 中 function 也是 Object,因此最全面的判断是否为对象的自定义函数为:

function isObject(value) {
  var type = typeof value;
  return value != null && (type == 'object' || type == 'function');
}

示例代码:

function isObject(value) {
  var type = typeof value;
  return value != null && (type == 'object' || type == 'function');
}

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
const auto = new Car('HongQi', 'H6', 2020);

console.log(isObject(auto));
// 输出为: true

使用 instanceof 判断变量是否为对象

JavaScript 的内置函数 instanceof 在判断变量的类型时,不只是判断创建变量的构造函数(constructor)的类型,同时判断在其原型类链(继承类)上是否存在一个构造函数(constructor)与当前需要匹配的类型相同。

在 js 中使用 instanceof 判断变量是否为对象的示例:

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
const auto = new Car('HongQi', 'H6', 2020);

console.log(auto instanceof Object);
// 输出为: true

结语

本文了介绍两种在 JS 中最实用、最简单的判断一个变量是否为对象的方法,分别是:js 基于 typeof 自定义函数判断一个变量是否为对象,js 使用 instanceof 判断一个变量是否为对象。