js 检测数据类型的三种方式

1、typeof

typeof 用以获取一个变量或者表达式的类型,typeof 一般只能返回如下几个结果:

typeof "John"                 // 返回 string
typeof 3.14                   // 返回 number
typeof NaN                    // 返回 number
typeof false                  // 返回 boolean
typeof [1,2,3,4]              // 返回 object
typeof {name:'John', age:34}  // 返回 object
typeof new Date()             // 返回 object
typeof function () {}         // 返回 function
typeof myCar                  // 返回 undefined (如果 myCar 没有声明)
typeof null                   // 返回 object

请注意:

  • NaN 的数据类型是 number
  • 数组(Array)的数据类型是 object
  • 日期(Date)的数据类型为 object
  • null 的数据类型是 object
  • 未定义变量的数据类型为 undefined

如果对象是 JavaScript Array 或 JavaScript Date ,我们就无法通过 typeof 来判断他们的类型,因为都是 返回 object。

我们可以使用 typeof 来获取一个变量是否存在,如 if(typeof a!="undefined"){},而不要去使用 if(a) 因为如果 a 不存在(未声明)则会出错。

正因为 typeof 遇到 null,数组,对象时都会返回 object 类型,所以当我们要判断一个对象是否是数组时。

或者判断某个变量是否是某个对象的实例则要选择使用另一个关键语法 instanceof。

2、instanceof

可通过 instanceof 操作符来判断对象的具体类型,语法格式:

扫描二维码关注公众号,回复: 8310535 查看本文章
var result = objectName instanceof objectType

返回布尔值,如果是指定类型返回 true,否则返回 false:

例:

arr = [1,2,3];
if(arr instanceof Array){
    document.write("arr 是一个数组");
} else {
    document.write("arr 不是一个数组");
}

3、constructor 属性

constructor 属性返回所有 JavaScript 变量的构造函数。

"John".constructor                 // 返回函数 String()  { [native code] }
(3.14).constructor                 // 返回函数 Number()  { [native code] }
false.constructor                  // 返回函数 Boolean() { [native code] }
[1,2,3,4].constructor              // 返回函数 Array()   { [native code] }
{name:'John', age:34}.constructor  // 返回函数 Object()  { [native code] }
new Date().constructor             // 返回函数 Date()    { [native code] }
function () {}.constructor         // 返回函数 Function(){ [native code] }

你可以使用 constructor 属性来查看对象是否为数组 (包含字符串 "Array"):

function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
}

你可以使用 constructor 属性来查看对象是否为日期 (包含字符串 "Date"):

function isDate(myDate) {
    return myDate.constructor.toString().indexOf("Date") > -1;
}

猜你喜欢

转载自www.cnblogs.com/art-poet/p/12098075.html