如何检查var是否是JavaScript中的字符串? [英] How can I check if a var is a string in JavaScript?

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

问题描述

如何检查var是否是JavaScript中的字符串?

How can I check if a var is a string in JavaScript?

我试过这个并且它不起作用...

I've tried this and it doesn't work...

var a_string = "Hello, I'm a string.";

if (a_string typeof 'string') {
    // this is a string
}


推荐答案

您已经关闭:

if (typeof a_string === 'string') {
    // this is a string
}






在相关说明中:如果使用 new String('hello')因为类型将是 Object 。有一些复杂的解决方案可以解决这个问题,但最好还是避免以这种方式创建字符串。


On a related note: the above check won't work if a string is created with new String('hello') as the type will be Object instead. There are complicated solutions to work around this, but it's better to just avoid creating strings that way, ever.

这篇关于如何检查var是否是JavaScript中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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