你未注重的typeof操作符

typeof能夠返回以下某個字符串

  1. “undefined” — 假如這個值未定義
  2. “boolean” — 假如這個值是布爾值
  3. “string” — 假如這個值是字符串
  4. “number” — 假如這個值是數值
  5. “object” — 假如這個值是對象或許null
  6. “function” — 假如這個值是函數

須要注重的幾種狀況

  1. typeof Infinity === ‘number’;
  2. typeof NaN === ‘number’; // 只管NaN是”Not-A-Number”的縮寫
  3. typeof (typeof 1) === ‘string’; // typeof老是返回一個字符串
  4. typeof undefined === ‘undefined’;
  5. typeof declaredButUndefinedVariable === ‘undefined’;
  6. typeof undeclaredVariable === ‘undefined’;

辨別數組,一般對象

  1. typeof [1, 2, 4] === ‘object’;
  2. typeof class C{} === ‘function’
  3. typeof Math.sin === ‘function’;
  4. typeof null === ‘object’; // 從一最先湧現JavaScript就是如許的

typeof為number舉例

  1. typeof 37 === ‘number’;
  2. typeof 3.14 === ‘number’;
  3. typeof Math.LN2 === ‘number’;
  4. typeof Infinity === ‘number’;
  5. typeof NaN === ‘number’;
  6. typeof Number(1) === ‘number’; // 不要運用這類情勢!

typeof為string舉例

  1. typeof “” === ‘string’;
  2. typeof “bla” === ‘string’;
  3. typeof (typeof 1) === ‘string’; // typeof老是返回一個字符串
  4. typeof String(“abc”) === ‘string’; // 不要運用這類情勢!

typeof為Booleans舉例

  1. typeof true === ‘boolean’;
  2. typeof false === ‘boolean’;
  3. typeof Boolean(true) === ‘boolean’; // 不要運用這類情勢!

typeof為Symbols舉例

  1. typeof Symbol() === ‘symbol’;
  2. typeof Symbol(‘foo’) === ‘symbol’;
  3. typeof Symbol.iterator === ‘symbol’;

typeof為Undefined舉例

  1. typeof undefined === ‘undefined’;
  2. typeof declaredButUndefinedVariable === ‘undefined’;
  3. typeof undeclaredVariable === ‘undefined’;

typeof為Objects舉例

  1. typeof {a:1} === ‘object’;
  2. typeof [1, 2, 4] === ‘object’;
  3. typeof new Date() === ‘object’;
  4. typeof null === ‘object’;

typeof為function舉例

  1. typeof function(){} === ‘function’;
  2. typeof class C{} === ‘function’
  3. typeof Math.sin === ‘function’;
  4. typeof new Function() === ‘function’;

發起不要運用的

  1. typeof new Boolean(true) === ‘object’;
  2. typeof new Number(1) === ‘object’;
  3. typeof new String(“abc”) === ‘object’;

參考文檔:MDN-typeof操作符

    原文作者:pitaojin
    原文地址: https://segmentfault.com/a/1190000015038606
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞