typeof 操作符
在开始typeof之前,先看一下基本的数据类型:
| 类型 | 说明 | 例子 | 
| 
 string  | 
字符串 | typeof "abc"; //string | 
| 
 number  | 
数值 | typeof 99; //number | 
| 
 boolean  | 
布尔值 | typeof false; //boolean | 
| 
 function  | 
函数 | 
 function test(){}; typeof test; //function  | 
| 
 undefined  | 
未定义 | 
 typeof undefined; //undefined typeof animal; //undefined  | 
| object | 对象或者是null | 
 typeof window; typeof {}; typeof []; typeof null;  | 
typeof操作符的作用呢就是看给定的变量是那种基本的数据类型,它的操作对象可以是字面量或者变量。
从表中,undefined项可知,对于未定义变量,通过typeof之后返回undefined。那么可以通过typeof判断变量是否被定义。
//animal 为被定义 console.log(typeof animal); //undefined
在开发中,对于未定义的变量,如果直接使用会报错,通过上面的特点可以有效避免错误:
//ReferenceError: animal is not defined if(animal){ console.log("animal"); } //改进版 if(typeof animal == "undefined"){ console.log("animal"); }
                    
                
                
            
        
浙公网安备 33010602011771号