javascript怎么判断是否为对象

判断方法:

1、使用toString()来判断;

2、使用“obj.constructor === Object”来判断;

3、使用“typeof obj === Object”来判断;

4、利用instanceof关键字来判断。

5、$.isPlainObject()
判断指定参数是否是一个纯粹的对象(所谓"纯粹的对象",就是该对象是通过"{}"或"new Object"创建的。)

1、toString() 第一选择!推荐!(注意里面的第一个object是小写 ’[object Object]‘ )

Object.prototype.toString.call()方法可以精准判断变量类型,它返回[object constructorName]的字符串格式,这里的constructorName就是call参数的函数名

let obj = {}

var res1 = Object.prototype.toString.call(obj) === '[object Object]'
console.log(res1); //true

var res2 = Object.prototype.toString.call(obj); 
console.log(res2); //[object Object] 
var a = NaN;
var b= '222';
var c = null;
var d = false;
var e = undefined;
var f = Symbol(); 
var arr = ['aa','bb','cc'];
var obj = { 'a': 'aa', 'b': 'bb', 'c': 'cc' }; 
var res = Object.prototype.toString.call(arr);
console.log(res); 
//[object Array] 
var res2 = Object.prototype.toString.call(obj); 
console.log(res2); //[object Object] 
var res3 = Object.prototype.toString.call(a);
 console.log(res3); //[object Number] 
 var res4 = Object.prototype.toString.call(b); 
 console.log(res4); //[object String] 
 var res4 = Object.prototype.toString.call(c); 
 console.log(res4); //[object Null] 
 var res5 = Object.prototype.toString.call(d); 
 console.log(res5); //[object Boolean] 
 var res6 = Object.prototype.toString.call(e); 
 console.log(res6); //[object Undefined] 
 var res7 = Object.prototype.toString.call(f); 
 console.log(res7); //[object Symbol]
 // JavaScript Document

2、constructor

var arr = ['aa','bb','cc'];
var obj = {
'a': 'aa',
'b': 'bb',
'c': 'cc'
};
console.log(arr.constructor === Array); //true
console.log(arr.constructor === Object); //false
console.log(obj.constructor === Object); //true

3、instanceof

注意:

使用instanceof可以用来判断一个变量是数组还是对象,原理如下:
数组也是对象的一种,因此用 arr instanceof Object 也为true。

var arr = new Array();
 
var arr = ['aa','bb','cc'];
 
var obj = { a: 'aa', b: 'bb', c: 'cc' };
 
console.log(arr instanceof Array); //true
 
console.log(arr instanceof Object); //true
 
console.log(obj instanceof Array); //false
 
console.log(obj instanceof Object); //true

4、typeof

我们能够使用typeof判断变量的身份,判断字符串得到string,数字和NaN得到number,函数会得到function等,但是判断数组,对象和null时都会得到object,详细请看js数据类型,这就是typeof的局限性,并不能准确的判断该变量的"真实身份"。

let obj = {}

typeof obj === Object

// 根据typeof判断对象也不太准确

//表达式                       返回值

typeof undefined//           'undefined'

typeof null  //              'object'

typeof true       //         'boolean'

typeof 123        //         'number'

typeof "abc"       //        'string'

typeof function() {} //      'function'

typeof {}             //     'object'

typeof []             //     'object'

5、$.isPlainObject()
判断指定参数是否是一个纯粹的对象(所谓"纯粹的对象",就是该对象是通过"{}"或"new Object"创建的。)

$.isPlainObject(obj) 

----------------------------

以下是对所有这些方法的整合,创建了一个综合性函数 isPlainObject,可以通过多种方式判断一个值是否为一个纯粹的对象。

代码实现:

/**
 * 判断是否为纯对象(Plain Object)
 * 纯对象是通过 '{}' 或 'new Object()' 创建的
 * 
 * @param {any} value - 要判断的值
 * @returns {boolean} - 如果是纯对象返回 true,否则返回 false
 */
function isPlainObject(value) {
  // 1. 排除 null 值
  if (value === null) return false;

  // 2. 使用 Object.prototype.toString 判断
  if (Object.prototype.toString.call(value) !== '[object Object]') {
    return false;
  }

  // 3. 使用 constructor 判断
  if (value.constructor !== Object) {
    return false;
  }

  // 4. 使用 instanceof 判断
  if (!(value instanceof Object)) {
    return false;
  }

  // 5. 使用 jQuery 的 $.isPlainObject 判断(如果需要 jQuery 支持)
  if (typeof jQuery !== 'undefined' && typeof jQuery.isPlainObject === 'function') {
    return jQuery.isPlainObject(value);
  }

  return true;
}

// 测试
console.log(isPlainObject({})); // true
console.log(isPlainObject(new Object())); // true
console.log(isPlainObject(Object.create(null))); // false
console.log(isPlainObject([])); // false
console.log(isPlainObject(null)); // false
console.log(isPlainObject(42)); // false
console.log(isPlainObject('string')); // false
console.log(isPlainObject(function () {})); // false
console.log(isPlainObject(new Date())); // false

各部分逻辑解释:

  1. 排除 null

    • 因为 typeof null === 'object',需要先排除掉。
  2. 使用 Object.prototype.toString

    • 可以精准判断变量的类型,返回 [object Object] 表示是纯对象。
    • 优势:即使对象是通过 Object.create(null) 创建的,也能正确判断。
  3. 使用 constructor

    • 判断对象的构造函数是否是 Object,但对于 Object.create(null) 的情况返回 false
  4. 使用 instanceof

    • 判断对象是否为 Object 的实例。但对于原型链被清除的对象(如 Object.create(null))会判断错误。
  5. 结合 jQuery 的 $.isPlainObject(可选):

    • 如果项目中使用了 jQuery,可以利用它内置的方法 $.isPlainObject,该方法能精确判断是否为纯对象。

对比各方法优缺点:

方法优点缺点
Object.prototype.toString精确判断数据类型,推荐作为首选对原型链清除的对象(如 Object.create(null))不准确
constructor简单易用,能排除数组、函数等对原型链清除的对象(如 Object.create(null))无效
instanceof判断对象是否是 Object 的实例同样对 Object.create(null) 无效
typeof判断基础数据类型,例如字符串、数字、布尔值不能准确区分数组、对象、null
$.isPlainObjectjQuery 提供的方法,功能强大,考虑多种边界情况依赖 jQuery,需引入外部库

推荐组合:

  • 使用 Object.prototype.toString 作为主判断方法,同时结合 constructorinstanceof 方法,确保兼容性。
  • 如需处理特殊情况(如 Object.create(null)),可以添加更严格的逻辑。

资料:

javascript如何判断变量是否为对象? - html中文网icon-default.png?t=O83Ahttps://m.html.cn/qa/javascript/11450.html

js判断是否为对象_街边吃垃圾的博客-CSDN博客_js判断是否为对象var obj = {};1、toString(推荐)Object.prototype.toString.call(obj) === '[Object Object]'2、constructorobj.constructor === Object3、instanceof 需要注意的是由于数组也是对象,因此用 arr instanceof Object 也为true...icon-default.png?t=O83Ahttps://blog.csdn.net/zhangjing0320/article/details/81230170

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南北极之间

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值