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

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

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 .

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? 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. In those cases, passing a String object rather than a string primitive may have unexpected consequences.

链接地址: http://www.djcxy.com/p/94978.html

上一篇: 拉姆达可以有isString吗?

下一篇: 简单的方法来检查一个变量是否是一个字符串?