判断变量是否为基本包装类型需结合多种方法:先用typeof排除原始值,再用Object.prototype.toString.call精确匹配[object String]、[object Number]、[object Boolean],并确保其为对象类型。

要判断一个变量是否为基本包装类型(String、Number、Boolean),关键在于区分它到底是原始值(如 "hello"、42、true),还是用 new 构造出来的对象(如 new String("hello"))。这两者在 typeof 和 instanceof 上表现不同,必须结合多种方式才能准确识别。
看 constructor 和 toString.call 的组合结果
这是最可靠的方式,能明确区分原始值和包装对象:
-
Object.prototype.toString.call(x)对原始值返回"[object String]"、"[object Number]"、"[object Boolean]" - 对包装对象也返回相同字符串,但此时
x.constructor === String/Number/Boolean为true - 而原始值的
constructor虽然也指向对应构造函数(因隐式装箱),但更稳妥的做法是结合typeof排除原始类型
用 instanceof 检查(适用于显式创建的包装对象)
instanceof 可直接识别由 new 创建的包装实例:
-
new String('a') instanceof String→true -
'a' instanceof String→false(原始字符串不是对象) -
new Number(123) instanceof Number→true -
123 instanceof Number→false
注意:instanceof 依赖原型链,在跨 iframe 环境下可能失效,一般场景下够用。
避免只依赖 typeof
typeof 无法区分原始值和包装对象:
-
typeof "abc"→"string" -
typeof new String("abc")→"object" -
typeof true→"boolean" -
typeof new Boolean(true)→"object"
所以单靠 typeof 只能确认是不是原始类型,不能确认是不是包装类型。若得到 "object",还需进一步验证是否为包装对象。
综合判断函数示例
可封装一个工具函数,兼顾准确性与实用性:
function isPrimitiveWrapper(value) {
if (value === null || typeof value !== 'object') return false;
const tag = Object.prototype.toString.call(value);
return tag === '[object String]' ||
tag === '[object Number]' ||
tag === '[object Boolean]';
}
这个函数排除了 null 和非对象,再用 toString.call 精确匹配三类包装对象。它不会把数组、普通对象或 Date 等误判为基本包装类型。

















