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

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

问题描述

如何确定变量是否为JavaScript中的字符串或其他内容?

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

推荐答案

您可以使用 typeof 运算符:

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 建议弃用原始对象包装

  1. The Google JavaScript Style Guide says to never use primitive object wrappers.
  2. Douglas Crockford recommended that primitive object wrappers be deprecated.

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

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