JS数据类型

来源:互联网 发布:越狱怎么清除所有数据 编辑:程序博客网 时间:2024/05/17 21:31

JS数据类型

在 JavaScript 中有 5 种不同的数据类型:

  • string
  • number
  • boolean
  • object
  • function

3 种不同的对象类型:

  • Object
  • Date
  • Array

2个不包含任何值的数据类型:

  • null
  • undefined

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。

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;}

constructor 属性

Number() 转换为数字, String() 转换为字符串, Boolean() 转化为布尔值。

原创粉丝点击