文章

typeof用法

typeof用法

typeof用法

1. typeof的语法

    typeof是一个运算符,有2种使用方式:typeof(表达式) 和 typeof 变量名,第一种是对表达式做运算,第二种是对变量做运算。

2、返回值

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

3、实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//string
typeof '123';
typeof (typeof 1); // typeof总是返回一个字符串
typeof String("abc"); // 不建议

//number
typeof 123;
typeof Math.LN2;
typeof Infinity;
typeof Number(1);
typeof NaN;

//boolean
typeof true;
typeof false;
typeof Boolean(true); // 不建议

//undefined
typeof a;
typeof abcde;
typeof undefined;
typeof undeclaredVariable; 
typeof declaredButUndefinedVariable;

//object
typeof null;;
typeof {a:1};
typeof [1, 2, 4];
typeof new Date()
typeof new Number(123); //不建议
typeof new String("abc"); //不建议

//function
typeof function(){};
typeof class c{};
typeof Math.sin;

// Symbols
typeof Symbol() === 'symbol';
typeof Symbol('foo') === 'symbol';
typeof Symbol.iterator === 'symbol';

//特殊中的特殊
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"

4、typeof为什么要区分object和function?

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

  2. 答案二:在实际的使用过程中有必要区分Object和Function,所以在typeof这里实现了

5、不足之处

  1. 不能区分对象、数组、正则,对它们操作都返回”object”;(__正则在Safar5,Chrome7之前的版本中返回”function”)

  2. Safar5,Chrome7之前的版本对正则对象返回 ‘function’

  3. 在IE6,7和8中,大多数的宿主对象是对象,而不是函数;如:typeof alert; //object

  4. 而在非ID浏览器或则IE9以上(包含IE9),typeof alert; //function

注意:null 和 undefined 的值相等,但类型不等:null === undefined // false; null == undefined  // true

本文由作者按照 CC BY 4.0 进行授权