有很多,但最常用的就是typeof操作符和Object.prototype.toString方法。typeof操作符可以用来判断基本类型,如:string、number、boolean、undefined、null,而Object.prototype.toString方法可以用来判断复杂类型,如:Array、Object、Date等。
1、typeof操作符:
typeof操作符可以用来判断基本类型,如:string、number、boolean、undefined、null,可以使用下面的方法:
let str = 'hello';
let num = 1;
let bool = true;
let undef = undefined;
let nul = null;
console.log(typeof str); // string
console.log(typeof num); // number
console.log(typeof bool); // boolean
console.log(typeof undef); // undefined
console.log(typeof nul); // object
2、Object.prototype.toString方法:
Object.prototype.toString方法可以用来判断复杂类型,如:Array、Object、Date等,可以使用下面的方法:
let arr = [1,2,3];
let obj = {a:1,b:2};
let date = new Date();
console.log(Object.prototype.toString.call(arr)); // [object Array]
console.log(Object.prototype.toString.call(obj)); // [object Object]
console.log(Object.prototype.toString.call(date)); // [object Date]
:有很多,但最常用的就是typeof操作符和Object.prototype.toString方法。typeof操作符可以用来判断基本类型,而Object.prototype.toString方法可以用来判断复杂类型。