好久沒有寫博客了,現在重新開始。今天寫的是一個關於JavaScript類型判斷的問題
JavaScript判斷類型常見的是有四種方法——typeof,toString,instanceof和constructor
本次主要說typeof和toString
type
typeof用於區分對象和原始類型
基本類型
function test(o){
console.log(typeof o)
}
test(undefined);
test(null);
test(3);
test("Sadf");
test({});
test(true)
運行結果爲
可以看到,typeof在基本類型上除了null還是不錯的
其它類型
// Symbols
typeof Symbol() === 'symbol'
typeof Symbol('foo') === 'symbol'
typeof Symbol.iterator === 'symbol'
// Undefined
typeof undefined === 'undefined';
typeof declaredButUndefinedVariable === 'undefined';
typeof undeclaredVariable === 'undefined';
// Objects
typeof {a: 1} === 'object';
// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
typeof [1, 2, 4] === 'object';
typeof new Date() === 'object';
// The following is confusing. Don't use!
typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String('abc') === 'object';
// Functions
typeof function() {} === 'function';
typeof class C {} === 'function';
typeof Math.sin === 'function';
下面讓我們看看toString的情況
toString
function toStr(o){
console.log(toString.call(o))
}
toStr(undefined);
toStr(null);
toStr(3);
toStr("adf");
toStr(true);
toStr(Symbol("adsf"))
這一次返回結果還讓人滿意,讓我們進行更復雜的測試
toString.call(new Date); // [object Date]
toString.call(new String); // [object String]
toString.call(Math); // [object Math]
// Since JavaScript 1.8.5
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]
toString.call(()=>{console.log("hello")) //[object Function]
toString.call(class A{}) //[object Function]
toString.call(new Number("123")) //[object Number]