1.六种数据类型
弱类型特性:
var num = 32;
32+num // 64
"32"+num // "3232"
"32"-num // 0
六种基础类型:五种原始类型+一种队形类型;
五种原始类型:number、string、boolean、null、undefined。
对象类型:object包含Function、Array、Date...多种类型。
2.隐式转换
2.1、+和-号
var x = ‘The answer is’+42; //字符串拼接
var y = 42 + ‘is the answer’;
‘37’ - 7 //30
‘37’+7 //377
2.2、巧用+/-规则转换类型
var num = ‘10’ 转换number num - 0;
var num = 10 转换string num+“”;
2.3、等于和严格等于
“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(引用去比较对象)
非严格等于==
类型不同,尝试类型转换和比较
null == undefined 相等
number == string 转换number 1 == “1.0” //true
boolean == ? 转换number 1 == true //true
object == number|string 尝试对象转为基本类型 new String(‘hello’)== ‘hello’ //true
其他:false
3.包装对象
var a = “string”;
alert(a.lenght);//6
a.t = 3;
alert(a.t); //undefined
4.类型检测
4.1、typeof
适合基本类型及function检测,遇到null失效,返回object
typeof 100 “number”
typeof true "boolean"
typeof function "funciton"
typeof(undefined) "undefined"
typeof new Object() "object"
tyoeof[1,2] "objcet"
typeof NaN "number"
typeof null "object"
typeof null === "object"(历史遗留问题)
4.2、instanceof
适合自定义对象,也可用来检测原生对象,在不同iframe和window间检测时失效。
obj instanceof object(判断对象)
[1,2] instanceof Array === true
new Object() instanceof = false
注意:不同额window或者iframe间的对象类型检测不能使用inftanceof
4.3
通过{}.toString拿到,适合内置对象和基本元素,遇到null和undefined失效(IE678等返回[object Object]})
Objcet.prototype.toString.apply([]); ==="[objcet Array]";
Objcet.prototype.toString.apply(function[]); ==="[objcet Function]";
Objcet.prototype.toString.apply(null); ==="[objcet Null]";
Objcet.prototype.toString.apply(undefined); ==="[objcet undefined]";
注意:IE6/7/8 Objcet.prototype.toString.apply(null) 返回“[object Object]”
4.4、
constructor
4.5
duck type