JavaScript中的数据类型和判断类型的方法
js有哪些类型?
JavaScript中一共有9中数据类型,其中包含五种基本类型和一种复杂类型Object,Object中包含四种类型。
- 基本数据类型
- 字符串(string)
- 数字(number)
- 布尔(boolean)
- NULL
- Undefined
- 复杂数据类型
- Symbol(表示一个独一无二的值)
- 对象(object)
- 数组(array)
- 函数(function)
如何判断一个变量的类型
-
使用typeof判断变量类型。
console.log( typeof num,//num typeof str,//string typeof bool,//boolean typeof arr,//object typeof json,//object typeof func,//function typeof und,//undefined typeof nul,//object typeof date,//object typeof reg,//object typeof error //object ); -
使用instanceof判断变量类型
instanceof和typeof运算符相似,用于识别正在处理的对象类型。与typeof方法不同的是,instanceof方法要求开发者明确地确认对象为某特定类型。function Person(){ } var Tom = new Person(); console.log(Tom instanceof Person); //必须使用Tom instanceof Person 明确确认对象为Person类型,不可以直接instanceof(Tom)进行判断 // true -
使用jQuery中的$.type()方法
console.log( $.type(num), $.type(str), $.type(bool), $.type(arr), $.type(json), $.type(func), $.type(und), $.type(nul), $.type(date), $.type(reg), $.type(error) ); // number string boolean array object function undefined null date regexp error

浙公网安备 33010602011771号