下面是typeof运算符的示例。
<script> //"string" document.write( typeof 'mukul' + "<br>" ) //"number" document.write( typeof 25 + "<br>" ) //"undefined" document.write( typeof variable) </script>
输出如下:
string number undefined
在JavaScript中, typeof运算符以字符串形式返回其操作数的数据类型。操作数可以是任何对象, 函数或变量。
语法如下:
typeof operand
OR
typeof (operand)
注意:操作数是表示要返回其类型的对象或基元的表达式。
javascript中存在的可能类型为:
- 未定义
- Object
- boolean
- Number
- String
- 符号
- 函数
例子:
<script>
//"string"
document.write( typeof 'mukul' + "<br>" )
//"number"
document.write( typeof 25 + "<br>" )
//"undefined"
document.write( typeof variable)
</script>
输出如下:
string
number
undefined
让我们一一涵盖所有类型, 为每个代码指定一个代码部分。
例子:Typeof Number, 在此示例中, 我们使用了" ==="(严格相等比较运算符), 该运算符比较值并同时键入两者, 然后返回true或false。例如, 考虑第一个console.log(), js开始从左到右编译, 它首先计算25的类型, 即"数字", 然后将其与"数字"进行比较, 然后最终返回true或false。
<script>
//Number
console.log( typeof 25 === 'number' );
console.log( typeof 3.14 === 'number' );
console.log( typeof (69) === 'number' );
//log base 10
console.log( typeof Math.LN10 === 'number' );
console.log( typeof Infinity === 'number' );
//Despite being "Not-A-Number"
console.log( typeof NaN === 'number' );
//Wrapping in Number() function
console.log( typeof Number( '100' ) === 'number' );
</script>
输出如下:

有趣的事实代表非数字的NaN具有"数字"的类型。
例子:字符串类型
<script>
//string
console.log( typeof '' === 'string' );
console.log( typeof 'bla' === 'string' );
//ES6 template literal
console.log( typeof `template literal` === 'string' );
console.log( typeof '1' === 'string' );
console.log( typeof ( typeof 1) === 'string' );
//Wrapping inside String() function
console.log( typeof String(1) === 'string' );
</script>
输出如下:

例如:布尔类型
<script>
//Boolean
console.log( typeof true === 'boolean' );
console.log( typeof false === 'boolean' );
//Two calls of the ! (logical NOT) operator
//are equivalent to Boolean()
console.log( typeof !!(1) === 'boolean' );
</script>
输出如下:

例子:类型未定义
<script>
//Undefined
console.log( typeof undefined === 'undefined' );
//Declared but undefined variable
console.log( typeof variable === 'undefined' );
</script>
输出如下:

例子:符号类型
<script>
//Symbol
console.log( typeof Symbol() === 'symbol' );
console.log( typeof Symbol( 'party' ) === 'symbol' );
console.log( typeof Symbol.iterator === 'symbol' );
</script>
输出如下:

例子:对象类型
<script>
//Object
console.log( typeof {b: 1} === 'object' );
console.log( typeof [1, 2, 9] === 'object' );
console.log( typeof new Date() === 'object' );
</script>
输出如下:

例子:功能类型
<script>
//function
console.log( typeof function () {} === 'function' );
//classes too are objects
console.log( typeof class C {} === 'function' );
console.log( typeof Math.sin === 'function' ); sin function (maths)
</script>
输出如下:
