JavaScript 型別判斷 instanceof typeof Object.prototype.toString.call([])
阿新 • • 發佈:2019-02-05
型別
- 基本型別 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"