javaScript 中如何检测一个变量是一个 String 类型?

本文介绍了在JavaScript中检测一个变量是否为String类型的方法:1. 使用typeof操作符,会返回'string';2. 查看变量的constructor属性;3. 利用Object.prototype.toString.call(),它能区分基本类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

javaScript 中如何检测一个变量是一个 String 类型?

答案:三种方法(typeof、constructor、Object.prototype.toString.call())

1.你可以使用 typeof 操作符来检测变量的数据类型。

  • typeof运算符的返回类型为字符串,值包括如下几种:

    • 'undefined' --未定义的变量或值

    • 'boolean' --布尔类型的变量或值

    • 'string' --字符串类型的变量或值

    • 'number' --数字类型的变量或值

    • 'object' --对象类型的变量或值,或者null(这个是js历史遗留问题,将null作为object类型处理)

    • 'function' --函数类型的变量或值

    typeof是一个运算符,有2种使用方式:typeof(表达式)和typeof 变量名,第一种是对表达式做运算,第二种是对变量做运算。

typeof('123') === "string" // true

typeof '123' === "string" // true

2.constructor 属性返回对创建此对象的数组函数的引用。

<script type="text/javascript">

var test=new Array();

if (test.constructor==Array)
{
document.write("This is an Array");
}
if (test.constructor==Boolean)
{
document.write("This is a Boolean");
}
if (test.constructor==Date)
{
document.write("This is a Date");
}
if (test.constructor==String)
{
document.write("This is a String");
}

'123'.constructor === String // true

</script>

3.Object.prototype.toString.call()

Object.prototype.toString.call('123') === '[object String]' // true

JavaScript里使用typeof判断数据类型,只能区分基本类型,即:numberstringundefinedbooleanobject。 对于nullarrayfunctionobject来说,使用typeof都会统一返回object字符串。 要想区分对象、数组、函数、单纯使用typeof是不行的。在JS中,可以通过Object.prototype.toString方法,判断某个对象之属于哪种内置类型。 分为nullstringbooleannumberundefinedarrayfunctionobjectdatemath

Object.prototype.toString.call(``null``); ``// "[object Null]"
Object.prototype.toString.call(undefined); ``// "[object Undefined]"
Object.prototype.toString.call(“abc”);``// "[object String]"
Object.prototype.toString.call(123);``// "[object Number]"
Object.prototype.toString.call(``true``);``// "[object Boolean]"

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值