类型
- 基本类型 number, string, bool, null, undefined, 访问的是值。
- 复杂类型 array, function, object, 访问的是值的引用
//基本类型
var a = 5;
var b = a;
b = 6;
a; //5
b; //6
//复杂类型
var a = ['hehe', 'haha'];
var b = a;
b[0] = 'heihei';
a[0]; //'heihei'
b[0]; //'heihei'
类型判断
1 new String Vs “string”
var a = 'bilibili';
var b = new String('bilibili');
a + b; //'bilibilibilibili'
//方法1
a instanceof String; //false
b instanceof String; //true
a.substr == b.substr; //true 两个变量确实都是字符串
//方法2
typeof a; //"string"
typeof b; //"object"
//方法3 ==
a == b; //true
a === b; //false
//方法4 对象内部的[[Class]]值,该值不可变。推荐此方法
Object.prototype.toString.call(a); //"[object String]"
Object.prototype.toString.call(b); //"[object String]"
所以正如《JavaScript : The Good parts》《JavaScript : 精粹》所说的,应避免使用new。
2 Array Vs Object (怎么判断变量是否为array)
var a = ['dog', 'cat'];
var b = new Array(['dog', 'cat']);
a == b; //true
a === b; //false
//方法1
a instanceof Array; //true
b instanceof Array; //true
//方法2 注意!array 会被判断为"object",不能用此方法
typeof a; //"object"
typeof b; //"object"
//方法3 es5的标准,被IE9+支持
Array.isArray(a); //true
Array.isArray(b); //true
//方法4 对象内部的[[Class]]值,该值不可变。推荐此方法
Object.prototype.toString.call(a); //"[object Array]"
Object.prototype.toString.call(b); //"[object Array]"
小心避免使用 方法2 typeof去判断array,难以与object区分开来。应用方法4.
3 true Vs false
var a = 0;
var b = null;
var c; //undefined
var d = '';
//注意!null 会被判断为"object"
typeof a; //"number"
typeof b; //"object"
typeof c; //"undefined"
typeof d; //"string"
a == false; //true 注意!
a === false; //false
b == false; //false
c == false; //false
d == false; //true 注意!
d === false; //false
//if 语句内 都会判断为false
if(a) {console.log("true");} //不会执行console.log("true");
if(b) {console.log("true");} //不会执行console.log("true");
if(c) {console.log("true");} //不会执行console.log("true");
if(d) {console.log("true");} //不会执行console.log("true");
4 typeof 的坑
从 2和3中,就可以看出typeof 在array和null的坑
var a = ['dog', 'cat'];
var b = null;
typeof a; //"object"
typeof b; //"object"