本文目录导读:
判断变量类型是编程中的基础操作,不同语言实现方式不同,以下按主流语言分类说明:
JavaScript
typeof操作符(最常用)typeof 42 // "number" typeof "hello" // "string" typeof true // "boolean" typeof undefined // "undefined" typeof null // "object" (语言历史遗留问题) typeof [] // "object" typeof {} // "object" typeof function(){} // "function" typeof Symbol() // "symbol"Object.prototype.toString.call()(精准判断内置类型)Object.prototype.toString.call([]) // "[object Array]" Object.prototype.toString.call(null) // "[object Null]"
instanceof(判断对象是否属于某个类)[] instanceof Array // true {} instanceof Object // true
Python
type()函数(返回类型对象)type(42) # <class 'int'> type("hello") # <class 'str'>isinstance()函数(推荐,支持继承关系)isinstance(3.14, (int, float)) # True(浮点数也属于数字) isinstance([1,2], list) # True
__class__属性(42).__class__ # <class 'int'>
Java
instanceof关键字(编译时检查继承关系)if (obj instanceof String) { // 处理字符串 }getClass()方法(精确获取运行时类)obj.getClass() // 返回 Class 对象,String.class obj.getClass().getName() // "java.lang.String"
isInstance()方法(反射方式,类似instanceof)String.class.isInstance(obj) // true/false
Go
- 类型断言(用于接口值)
var i interface{} = "hello" v, ok := i.(string) // v="hello", ok=true - 反射(
reflect包)reflect.TypeOf(42) // int reflect.ValueOf(3.14).Kind() // float64
C++
typeid关键字(需要<typeinfo>)#include <typeinfo> std::cout << typeid(42).name(); // 打印类型名(可能被修饰,如 "i" 表示int)
dynamic_cast(运行时检查多态类型)if (Derived* d = dynamic_cast<Derived*>(basePtr)) { // basePtr 实际指向 Derived 类型 }
TypeScript
- 类型守卫(编译时基于代码逻辑推断)
function isString(value: unknown): value is string { return typeof value === "string"; } typeof/instanceof(运行时用法同 JavaScript)as断言(编译时手动指定类型,不检查运行时)
通用注意事项
null的特殊性:在 JavaScript 中typeof null === "object",需额外判断。- 数组与对象的区分:推荐用
Array.isArray()(JS)或list类型检查(Python)。 - 基础类型 vs 包装类型:如 JS 的
new String("a")和原始字符串"a"类型不同。 - 语言差异:动态语言(JS/Python)依赖运行时类型,静态语言(Java/C++)在编译期已有类型信息。
最佳实践:优先使用语言自带、性能较高的方法(如 isinstance/typeof),仅在需要精确区分时使用反射或复杂检查。
标签: instanceof