1.typeof操作符的基本概念
typeof操作符是干什么用的?用于检测给定变量的数据类型。
为什么要检测?因为ECMASCript是松散类型的,变量可以存放任何数据类型的值。
2.typeof操作符基本用法
| 返回的字符串值 | 返回值意义 |
| "undefined" | 变量值未定义,变量值等于undefined |
| "boolean" | 变量值的类型是Boolean类型,布尔值 |
| "string" | 变量值是字符串 |
| "number" | 变量值是数值,Number类型 |
| "object" | 变量值是对象或者null |
| "function" | 变量值是函数 |
var a;
typeof a; // "undefined"
a =true;
typeof a; //"boolean"
a = "message";
typeof a; //"string"
a = 11;
typeof a; //"number"
a = null;
typeof a; //"object"
a = {};
typeof a; //"object"
a = function(){
console.log("1");
}
typeof a; //"function"
3.typeof操作符需要注意的几点
- typeof 操作符可以直接操作数值字面量。
typeof 11;
typeof "msg";
typeof true;
typeof null;
typeof {};
typeof function(){
console.log("1");
}
-
typeof null;// "object",是因为null表示空对象的指针。
-
function是Object,为什么返回"function"而不是"object"?
从技术角度讲,函数在ECMAScript中是对象,不是一种数据类型。然而,函数也确实有一些特殊的属性,因此通过typeof操作符来区分函数和其他对象是有必要的。
-
typeof typeof true; // "string",typeof返回的是字符串
本文详细介绍了ECMAScript中typeof操作符的基本概念、使用方法及注意事项。typeof操作符用于检测变量的数据类型,包括基本数据类型如undefined、boolean、string、number等,以及复杂数据类型如object和function。此外还探讨了特殊情况下typeof的返回值。
478

被折叠的 条评论
为什么被折叠?



