JavaScript 数据类型
在 JavaScript 中有 5 种不同的数据类型:
- string
- number
- boolean
- object
- function
3 种对象类型:
- Object
- Date
- Array
2 个不包含任何值的数据类型:
- null
- undefined
typeof 操作符
你可以使用 typeof 操作符来查看 JavaScript 变量的数据类型。
实例
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 (if myCar is not declared)
typeof null // 返回 object
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 (if myCar is not declared)
typeof null // 返回 object
请注意:
- NaN 的数据类型是 number
- 数组(Array)的数据类型是 object
- 日期(Date)的数据类型为 object
- null 的数据类型是 object
- 未定义变量的数据类型为 undefined
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] }
( 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] }