本文主要是介绍js中typeof的用法与说明,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
typeof是一个一元运算符,返回的是字符串,对于不同的操作数,返回的结果不同。
使用
typeof是一个运算符,有2种使用方式:
- typeof(表达式):对表达工做运算。
- 和typeof(变量名):对变量做运算。
返回值
返回值的返回类型是字符串
- ‘undefined’ ----未定义的变量或值
- ‘boolean’ ----布尔类型的变量或值
- ‘string’ ----字符串类型的变量或值
- ‘number’ -----数字类型的变量或值
- ‘object’ -----对象类型的变量或值,或者null(js遗留问题,将null作为object类型处理)
- ‘function’ ----函数类型的变量或值
- ’symbol’ -----ES6提供的新的类型
举例子
typeof语法中的圆括号是可选项,如 typeof 123 等同于 typeof(123)。
typeof运算符把数组,对象或者null返回object。
//Numbers
typeof 12; //'number'
typeof 2.12; //number'
typeof(212);//'number'
typeof Math.LN2;//'number' Math.LN2属性表示2的自然对数 Math.LN2=ln(2);约为0.693;
typeof Infinity;//'number' Infinity不是常量,该属性是用于存放表示正无穷大的数值。如:var t1=1.25688745852369E+1023589;console.log(t1)//Infinity
typeof NaN;//'number'
typeof Number(212);//212//Strings
typeof '';//'string'
typeof 'hello';//'string'
typeof '123' ;// 'string'
typeof (typeof 1) ;//'string' typeof 1返回的是字符串'number' typeof('number')==='string'
typeof string(123);//'123'//Booleans
typeof true;//'boolean'
typeof false;//'boolean'
typeof Boolean(true);//'boolean'//Undefined
typeof undefined;//'undefined'
typeof aaa;//'undefined'
var aaa;typeof aaa;//'undefined';//在js中,没有值的变量,其值是undefined.typeof也返回undefined.
var aaa='';typeof aaa;//'string'; 空值与undefined不一样。空的字符串既有值也有类型。//Symbols
typeof Symbol();//'symbol'
typeof Symbol('foo');//'symbol'
typeof Symbol.iterator;//'symbol'//Objects
typeof {a:1};//'boject'
typeof [1,2,3];//'object' typeof运算符对数组返回'object',因为是js中数组属于对象
typeof new Date();//'object'
typeof null;//'object'
typeof new Boolean(true);//'object'
typeof new Number(1);//'object'
typeof new String('abc')'//'object'
typeof /a/;//'object'
var aaa=null; typeof aaa //'object' //Functions
typeof function(){};//'function'
typeof class c {};//'function'
typeof Math.sin;//'function'
注意
我们在平时使用中,判断一个变量是否存在,经常会用if()来判断。比如:
- 判断一个变量是否存在: if(a){}; 如果a不存在/或者a未声明,则会出错。工作台会出现 Uncaught ReferenceError:a is not defined;
- 判断一个对象是否存在:var list={ name:‘sxx’ };如果是一个对象。if(storeList.name){} 工作台会出现 storeList is not defined;if(storeList != ‘undefiend’){} 也会提示storeList is not defined; 正确用法 if(typeof storeList !=‘undefined’){} 就不会出错了。
- 对于Array,Null等特殊对象使用typeof一律返回object,这是typeof的局限性。
- 判断一个对象是否是数组:instanceof用于判断一上变量是否某个对象的实例,如var a=new Array();console.log(a instanceof Array) ,返回true;console.log(a instanceof Object)也返回true;这是因为Array是Object的子类。a instanceof Object返回true并不是因为Array是Object的子对象,而是因为Array的prototype属性构造于object,Array的父级是Function。
这篇关于js中typeof的用法与说明的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!