检查变量是否为字符串的简便方法? [英] Easy way to check if a variable is a string?

查看:105
本文介绍了检查变量是否为字符串的简便方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是 []的衍生产品。数组的实例但是不是字符串

鉴于

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

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

然后,如果我有一个变量 abc 我想知道它是否是一个字符串,我可以做

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]是最短/最本地的做法

I think Object.prototype.toString.call(a) === "[object String]" is the shortest/nativest way of doing this

这篇关于检查变量是否为字符串的简便方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆