JavaScript 中如何检测一个变量是 String 类型?

1. typeof

最直接,注意 typeof 对基本类型字符串和包装对象都返回 'string'。

typeof('123') === 'string'; // true
typeof '123'  === 'string'; // true
typeof new String('123') === 'string'; // true

2. constructor

'123'.constructor === String;           // true
(new String('123')).constructor === String; // true

注意:原型被改写后会失效,且 constructor 容易被覆盖,谨慎使用。

3. Object.prototype.toString.call()

最严谨,可区分多种内置类型。返回 '[object String]'。

Object.prototype.toString.call('123') === '[object String]'; // true
Object.prototype.toString.call(new String('123')); // '[object String]'
Object.prototype.toString.call(123); // '[object Number]'

补充:实际开发中的最佳实践:

  • 简单判断用 typeof x === 'string',足够覆盖大多数场景。
  • 需要同时校验多种类型时,用 Object.prototype.toString.call(x).slice(8, -1) === 'String',或封装一个通用 getType 函数。
  • 表单输入值通常用 typeof x === 'string' 即可,因为 <input> 取出的都是基本类型字符串。
  • instanceof String 对字面量字符串返回 false,对 new String() 返回 true,不推荐用于判断基本类型字符串。

来源整理自:vue3js.cn 面试官系列