在JavaScript中,要输出一个元素的类型,通常可以使用typeof
操作符或者Object.prototype.toString.call()
方法。
typeof
操作符typeof
操作符可以返回一个表示操作数类型的字符串。对于基本数据类型(如字符串、数字、布尔值、undefined、function)和对象类型(如数组、日期等),typeof
会返回相应的类型字符串。
示例代码:
console.log(typeof 'hello'); // "string"
console.log(typeof 123); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof function() {}); // "function"
console.log(typeof {}); // "object"(注意:对于数组和null也会返回"object")
console.log(typeof []); // "object"
console.log(typeof null); // "object"(这是一个历史遗留问题)
注意:typeof
对于数组和null
都会返回"object"
,这并不是我们期望的结果,所以对于这两种情况,我们需要使用其他方法来判断。
Object.prototype.toString.call()
方法这个方法可以返回一个表示对象类型的字符串,格式为"[object Type]"
,其中Type
是对象的类型。
示例代码:
console.log(Object.prototype.toString.call('hello')); // "[object String]"
console.log(Object.prototype.toString.call(123)); // "[object Number]"
console.log(Object.prototype.toString.call(true)); // "[object Boolean]"
console.log(Object.prototype.toString.call(undefined)); // "[object Undefined]"
console.log(Object.prototype.toString.call(function() {})); // "[object Function]"
console.log(Object.prototype.toString.call({})); // "[object Object]"
console.log(Object.prototype.toString.call([])); // "[object Array]"
console.log(Object.prototype.toString.call(null)); // "[object Null]"
使用Object.prototype.toString.call()
方法可以准确地判断出数组和null
的类型。
typeof
操作符来判断类型。null
),建议使用Object.prototype.toString.call()
方法来判断类型,以获得更准确的结果。领取专属 10元无门槛券
手把手带您无忧上云