typeof
- 用于判断基本数据类型,只能返回如下几个结果:“number”、“string”、“boolean”、“object”、“function” 和 “undefined”。
运算数为数字 typeof(x) = “number”
字符串 typeof(x) = “string”
布尔值 typeof(x) = “boolean”
对象,数组和null typeof(x) = “object”
函数 typeof(x) = “function”
注意 故当类型不属于object 时才会给出详细情况类型,而且这个结果不会返回null
使用: typeof (变量 )
instanceof
用于判断引用类型的具体数据类型,判断一个变量是否是某个对象(类)的实例,返回值是布尔类型的。
使用: 变量 instanceof String
let str=new String("antzone");
console.log(str instanceof String); // true
本文介绍了JavaScript中使用typeof和instanceof进行类型检测的方法。typeof可以识别基本数据类型如数字、字符串等,而instanceof则用于判断对象的具体类型。通过具体示例展示了如何运用这两种方式来判断变量的数据类型。
1043

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



