检查变量是否是 JavaScript 中的字符串 [英] Check if a variable is a string in JavaScript

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

问题描述

如何确定一个变量是字符串还是 JavaScript 中的其他内容?

How can I determine whether a variable is a string or something else in JavaScript?

推荐答案

您可以使用 typeof 运算符:

You can use typeof operator:

var booleanValue = true; 
var numericalValue = 354;
var stringValue = "This is a String";
var stringObject = new String( "This is a String Object" );
alert(typeof booleanValue) // displays "boolean"
alert(typeof numericalValue) // displays "number"
alert(typeof stringValue) // displays "string"
alert(typeof stringObject) // displays "object"

来自此网页的示例.(尽管示例略有修改).

Example from this webpage. (Example was slightly modified though).

对于使用 new String() 创建的字符串,这不会按预期工作,但很少使用,建议不要使用 [1][2].如果您愿意,请参阅其他答案以了解如何处理这些问题.

This won't work as expected in the case of strings created with new String(), but this is seldom used and recommended against[1][2]. See the other answers for how to handle these, if you so desire.

  1. Google JavaScript 样式指南 说永远不要使用原始对象包装器.
  2. Douglas Crockford 建议弃用原始对象包装器.

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

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