简体   繁体   English

检查变量是否为字符串的简便方法?

[英]Easy way to check if a variable is a string?

This question is a spin-off of [] is an instance of Array but "" isn't of String 这个问题是[]的一个衍生产品, 是Array的一个实例,但“”不是String的实例

Given that 鉴于

"" instanceof String; /* false */
String() instanceof String; /* false */
new String() instanceof String; /* true */

and

typeof "" === "string"; /* true */
typeof String() === "string"; /* true */
typeof new String() === "string"; /* false */

Then, if I have a variable abc and I want to know if it's a string, I can do 然后,如果我有一个变量abc ,我想知道它是否是一个字符串,我可以做

if(typeof abc === "string" || abc instanceof String){
    // do something
}

Is there a simpler, shorter and native way of doing this, or must I create my own function? 有没有更简单,更短和本地的方式,或者我必须创建自己的功能?

function isStr(s){
    return typeof s === "string" || s instanceof String;
}
if(isStr(abc)){
    // do something
}

我认为Object.prototype.toString.call(a) === "[object String]"是这样做的最短/本地方式

you are correct: 你是对的:

typeof myVar == 'string' || myVar instanceof String;

is one of the best ways to check if a variable is a string. 是检查变量是否为字符串的最佳方法之一。

You may be confused because [] is an array initialiser (often called an array literal) that is defined as creating an Array object , whereas '' is a string literal that is defined as creating a string primitive . 您可能会感到困惑,因为[]是一个数组初始化器 (通常称为数组文字),定义为创建一个Array 对象 ,而''是一个字符串文字 ,定义为创建一个字符串基元

A primitive isn't an instance of any kind of object, though it may be coerced to a related object for convenience. 基元不是任何类型对象的实例,但为方便起见,它可能被强制转换为相关对象。

A more important question is why an isString function should return true for both string primitives and string objects? 一个更重要的问题是为什么isString函数应该为字符串基元和字符串对象返回true? The use of string objects is (extremely?) rare, I would have thought that their use would infer special treatment and that you would want to differentiate between the two and not treat them the same. 字符串对象的使用是(非常?)罕见,我会认为它们的使用会推断出特殊处理,并且你想要区分两者而不是对它们进行相同处理。

It's far more common to ignore the Type of a variable and, where it's Type might vary, unconditionally convert it to the required Type, eg if you want a string primitive: 忽略变量的类型更为常见,并且,如果它的类型可能不同,则无条件地将其转换为所需的类型,例如,如果您需要字符串基元:

function foo(s) {
  s = String(s); // s is guaranteed to be a string primitive
  ...
}

The exception is where functions are overloaded and have different behaviour depending on whether a particular argument is a Function, Object or whatever. 例外情况是函数重载并具有不同的行为,具体取决于特定参数是函数,对象还是其他。 Such overloading is generally not considered a good idea, but many javascript libraries are dependent on it. 这种重载通常不被认为是一个好主意,但许多JavaScript库依赖于它。 In those cases, passing a String object rather than a string primitive may have unexpected consequences. 在这些情况下,传递String对象而不是字符串原语可能会产生意外后果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM