判断方法:
1、使用toString()来判断;
2、使用“obj.constructor === Object”来判断;
3、使用“ypeof 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)
资料:
javascript如何判断变量是否为对象? - html中文网https://m.html.cn/qa/javascript/11450.html