概述
在JavaScript编程中,我们经常需要对数据类型进行判断和处理。为了应对不同情况,可以利用以下四种常用方法:
-
使用
typeof操作符可以快速确定一个值的基本类型,适用于简单数据类型的判断,但对于引用类型除了函数之外,只会返回 "object"。 -
instanceof操作符用于检查一个对象是否是某个类的实例,适用于判断引用类型是否为指定类的实例。 -
Array.isArray()方法用于确定一个值是否为数组,适用于判断某个值是否为数组。 -
Object.prototype.toString.call()方法可以获取一个值的详细类型信息,包括原始类型和引用类型,适用于准确判断数据类型。
1. typeof 操作符:用于确定一个值的基本类型。
- 返回的结果是一个字符串,表示值的类型。
- 常见的结果包括 "number"、"string"、"boolean"、"undefined"、"object" 和 "function"。
console.log(typeof 123); // 输出 "number"
console.log(typeof "hello"); // 输出 "string"
console.log(typeof true); // 输出 "boolean"
console.log(typeof null); // 输出 "object"
console.log(typeof [1,2,3]); // 输出 "object"
let func = function() {};
console.log(typeof func); // 输出 "function"
也就是说,常见的简单数据类型,除了null,其他的都能准确给出类型,而对于引用类型,它只能判断准确地给出函数的类型。
2. instanceof 操作符:用于检查一个对象是否是某个类的实例。
- 返回一个布尔值,表示对象是否是指定类的实例。
function Person() {}
let person = new Person();
console.log(person instanceof Person); // 输出 true
let obj = {};
console.log(obj instanceof Object); // 输出 true
let str = new String();
console.log(str instanceof String); // 输出 true
let func = function() {};
console.log(func instanceof Function); // 输出 true
let num = 123
console.log(num instanceof Number); // 输出 false
我们可以看出,instanceof可以判断引用类型,而无法判断原始类型,
3. Array.isArray() 方法:用于确定一个值是否为数组。
- 返回一个布尔值,表示值是否为数组。
console.log(Array.isArray([]1,2,3)); // 输出 true
console.log(Array.isArray({})); // 输出 false
只能用于判断某个值是否是数组
4. Object.prototype.toString.call() 方法:用于获取一个值的详细类型信息。
- 返回一个字符串,表示值的详细类型信息,格式为 "[object 类型]"。
console.log(Object.prototype.toString.call(123)); // 输出 "[object Number]"
console.log(Object.prototype.toString.call('123')); // 输出 "[object String]"
console.log(Object.prototype.toString.call(true)); // 输出 "[object Boolean]"
console.log(Object.prototype.toString.call(null)); // 输出 "[object Null]"
console.log(Object.prototype.toString.call(undefined)); // 输出 "[object Undefined]"
console.log(Object.prototype.toString.call([1,2,3])); // 输出 "[object Array]"
console.log(Object.prototype.toString.call(function() {})); // 输出 "[object Function]"
console.log(Object.prototype.toString.call({})); // 输出 "[object Object]"