typeof能夠返回以下某個字符串
- “undefined” — 假如這個值未定義
- “boolean” — 假如這個值是布爾值
- “string” — 假如這個值是字符串
- “number” — 假如這個值是數值
- “object” — 假如這個值是對象或許null
- “function” — 假如這個值是函數
須要注重的幾種狀況
- typeof Infinity === ‘number’;
- typeof NaN === ‘number’; // 只管NaN是”Not-A-Number”的縮寫
- typeof (typeof 1) === ‘string’; // typeof老是返回一個字符串
- typeof undefined === ‘undefined’;
- typeof declaredButUndefinedVariable === ‘undefined’;
- typeof undeclaredVariable === ‘undefined’;
辨別數組,一般對象
- typeof [1, 2, 4] === ‘object’;
- typeof class C{} === ‘function’
- typeof Math.sin === ‘function’;
- typeof null === ‘object’; // 從一最先湧現JavaScript就是如許的
typeof為number舉例
- typeof 37 === ‘number’;
- typeof 3.14 === ‘number’;
- typeof Math.LN2 === ‘number’;
- typeof Infinity === ‘number’;
- typeof NaN === ‘number’;
- typeof Number(1) === ‘number’; // 不要運用這類情勢!
typeof為string舉例
- typeof “” === ‘string’;
- typeof “bla” === ‘string’;
- typeof (typeof 1) === ‘string’; // typeof老是返回一個字符串
- typeof String(“abc”) === ‘string’; // 不要運用這類情勢!
typeof為Booleans舉例
- typeof true === ‘boolean’;
- typeof false === ‘boolean’;
- typeof Boolean(true) === ‘boolean’; // 不要運用這類情勢!
typeof為Symbols舉例
- typeof Symbol() === ‘symbol’;
- typeof Symbol(‘foo’) === ‘symbol’;
- typeof Symbol.iterator === ‘symbol’;
typeof為Undefined舉例
- typeof undefined === ‘undefined’;
- typeof declaredButUndefinedVariable === ‘undefined’;
- typeof undeclaredVariable === ‘undefined’;
typeof為Objects舉例
- typeof {a:1} === ‘object’;
- typeof [1, 2, 4] === ‘object’;
- typeof new Date() === ‘object’;
- typeof null === ‘object’;
typeof為function舉例
- typeof function(){} === ‘function’;
- typeof class C{} === ‘function’
- typeof Math.sin === ‘function’;
- typeof new Function() === ‘function’;
發起不要運用的
- typeof new Boolean(true) === ‘object’;
- typeof new Number(1) === ‘object’;
- typeof new String(“abc”) === ‘object’;