跳到主要内容

列举JavaScript中的数据类型检测方案 ?

参考答案:

在JavaScript中,有多种方法可以检测数据类型。以下是一些常见的方法:

  1. typeof

typeof运算符返回一个表示未定义变量、null、布尔值、数字、字符串、对象或函数的字符串。但是,它对于数组和null都返回"object",因此不能准确地区分它们。

console.log(typeof "abc"); // 输出 "string"
console.log(typeof 123);   // 输出 "number"
console.log(typeof true);  // 输出 "boolean"
console.log(typeof undefined); // 输出 "undefined"
console.log(typeof {a: 1}); // 输出 "object"
console.log(typeof []); // 输出 "object"
console.log(typeof null); // 输出 "object"
console.log(typeof function(){}); // 输出 "function"
  1. instanceof

instanceof运算符用于检测构造函数的prototype属性是否出现在对象的原型链中的任何位置。

let date = new Date();
console.log(date instanceof Date); // 输出 true

let array = [];
console.log(array instanceof Array); // 输出 true

注意,instanceof不能正确检测原始值类型,如字符串、数字和布尔值,因为它们的原型链中没有构造函数。 3. Object.prototype.toString.call()

这个方法可以获取到对象的[[Class]]内部属性,从而得到更为准确的类型信息。对于原始类型,Object.prototype.toString.call()会返回[object Type],其中Type是对应的具体类型。

console.log(Object.prototype.toString.call("abc")); // 输出 "[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(null)); // 输出 "[object Null]"
console.log(Object.prototype.toString.call({a: 1})); // 输出 "[object Object]"
console.log(Object.prototype.toString.call([])); // 输出 "[object Array]"
console.log(Object.prototype.toString.call(function(){})); // 输出 "[object Function]"

以上就是JavaScript中常见的几种数据类型检测方案。每种方案都有其优点和局限性,具体使用哪种方案取决于你的具体需求。