JavaScript中typeof详解

【范围】typeof返回值范围:

typeof返回值对应
类型 结果
String "string"
Number "number"
Boolean "boolean"
Undefined "undefined"
Object "object"
function函数对象 "function"
Symbol(ES6新增) "symbol"
宿主对象(由JS环境提供) Implementation-dependent

 

 

 

 

 

 

 

 

 

 

【typeof为什么要区分object和function?】

  1. 答案一:《JavaScript高级程序设计》:从技术角度讲,函数在ECMAScript中是对象,不是一种数据类型。然而,函数也确实有一些特殊的属性,因此通过typeof操作符来区分函数和其他对象是有必要的。
  2. 答案二:在实际的使用过程中有必要区分Object和Function,所以在typeof这里实现了

【typeof的不足之处】

  1. 不能区分对象、数组、正则,对它们操作都返回"object";(正则特殊一点后面说)
  2. Safar5,Chrome7之前的版本对正则对象返回 'function'
  3. 在IE6,7和8中,大多数的宿主对象是对象,而不是函数;如:typeof alert; //object
  4. 而在非ID浏览器或则IE9以上(包含IE9),typeof alert; //function

【记忆行为】

  1. 根据JS数据类型记忆String/Number/Boolean/Undefined/Object/function返回的字符串形式分别为:string/number/boolean/undefined/object/function
  2. 特殊记忆:
    1. Symbol(ES6新增)=> "symbol"
    2. 不能区分对象、数组、正则,返回"object",正则在Safar5,Chrome7之前的版本中返回"function"
    3. 宿主对象,IE6/7/8返回"object",其他浏览器返回"function"
    4. 特殊中的特殊
      typeof 1/0; //NaN(这个NaN不是字符串类型,是数值类型)
      typeof typeof 1/0; //NaN(这个NaN不是字符串类型,是数值类型)
      typeof(1/0); //"number"
      typeof typeof(1/0); //"string"
      typeof(typeof 1/0); //"number"

【题目和答案】

// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // 尽管NaN是"Not-A-Number"的缩写
typeof Number(1) === 'number'; // 但不要使用这种形式!

// Strings
typeof "" === 'string';
typeof "bla" === 'string';
typeof (typeof 1) === 'string'; // typeof总是返回一个字符串
typeof String("abc") === 'string'; // 但不要使用这种形式!

// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(true) === 'boolean'; // 但不要使用这种形式!

// 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';

// 使用Array.isArray 或者 Object.prototype.toString.call
// 区分数组,普通对象
typeof [1, 2, 4] === 'object';

typeof new Date() === 'object';

// 下面的容易令人迷惑,不要使用!
typeof new Boolean(true) === 'object';
typeof new Number(1) ==== 'object';
typeof new String("abc") === 'object';

// 函数
typeof function(){} === 'function';
typeof Math.sin === 'function';

//NaN
typeof 1/0 === 'NaN';

 

posted @ 2017-10-23 11:37  怪诞咖啡  阅读(45341)  评论(0编辑  收藏  举报