JavaScript 数据类型
1. 数据类型
弱类型特性
var num = 32;
num = "this is a string";
num 明明是number类型,为什么可以赋值成string
console.log(32 + 32) // 64
console.log("32" + 32) // 3232
console.log("32" - 32) // 0
“32” 加上 32 等于 “3232”,相减却等于0。
原始类型
-
number
-
string
-
boolen
-
null
-
undefined
-
object
-
Function
-
Array
-
Date
-
……
-
隐式类型转换
var x = 'The answer is ' + 42;
var y = 42 + ' is the answer';
"37" - 7 // 30
"37" + 7 // 377
巧用+/-规则转换类型
num - 0
和num - ''
将num转换为number或者string
==
类型相同,同===
类型不同,尝试类型转换和比较:null == undefined
object == number|string
会尝试将对象转换为基本类型new String('hi') == 'hi'
"1.23" == 1.23
0 == false
null == undefined
new Object() == new Object()
[1, 2] == [1, 2]
===
类型不同,返回 false
null === null
undefined === undefined
NaN ≠ NaN
new Object ≠ new Object
包装对象
var str = "string";
var strObj = new String("string");
str // "string"
strObj // {0: "s", 1: "t" …… , length: 6, [[PrimitiveValue]]: "string"}
当我们打印str.length
得到6,但它是一个基本类型不是对象为什么会有这样一个属性呢?
> str.t = 10
< 10
> str.t
< undefined
当我们将基础类型的值当作对象一样使用给他熟悉时,会智能的将基础类型转化为包装类型的临时对象,当完成访问以后,临时对象会被销毁掉。(123).toSting
一样可以将123转为"123"。
类型检测
typeof
typeof 100 // "number"
typeof true // "boolean"
typeof function // "function"
typeof(undefined) // "undefined"
typeof new Object() // "object"
typeof [1, 2] // "object"
typeof NaN // "number"
typeof null // "object"
instanceof
obj instanceof Object
[1, 2] instanceof Array === true
new Object() instanceof Array === false
Object.protype.toString
Object.prototype.toString.apply([]); // "[object Array]";
Object.prototype.toString.apply(function(){}); // "[object Function]"
Object.prototype.toString.apply(null); // "[object Null]";
Object.prototype.toString.apply(undefined); // "[object Undefined]";
-
typeof 适合基本类型及 function 检测,遇到 null 失效
-
[[Class]] 通过 {}.toString拿到,适合内置对象和基本类型,遇到 null 和 undefined 失效
-
instanceof 适合自定义对象,也可以用来检测原生对象,在不同 iframe 和 window 间检测失效