js中判断变量是否为字符串

本文介绍了三种JavaScript中判断变量是否为字符串的方法:1) 使用`typeof`操作符;2) 检查变量的构造函数是否为`String`;3) 利用`Object.prototype.toString.call()`进行高级检测。最后提供了多重验证方式以确保准确判断。

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

let str2 = “test”;

console.log( typeof(str2) == "string" ) ;   // true
console.log( str2.constructor === String  ) ;   // true , String是字符串类
console.log( Object.prototype.toString.call(str2) == "[object String]"  ) ;   // true

console.log( Object.prototype.toString(str2) ) ;   // [object Object]
console.log( Object.prototype.toString.call(str2) ) ;   // [object String]

1 基本方法(最常用也最简单)

typeof(str2)==‘string’

2 基本方法(简单)
str2.constructor===String

3 利用js原生函数(高级检测方法,但是有点复杂)

Object.prototype.toString.call(str2)=="[object String]"

(1)在 Object.prototype 这个 this (上下文环境)中执行toString()原生函数,会把里边的环境变量类型打印出来,如下:为 [object Object]
         Object.prototype.toString( str2 ) -->执行结果 -->"[object Object]"

(2)如果我们使用 call() 函数改变 this (上下文环境),就能打印出当前环境变量类型,根据这个类型来判断。
         Object.prototype.toString.call( str2 ) -->执行结果–>"[object String]"

浏览器中执行效果图:
在这里插入图片描述

4 多重验证

typeof( str2 ) == “string” && str2.constructor === String && Object.prototype.toString.call( str2) == “[object String]”

var str2 = "test";

console.log( typeof(str2) == "string" && str2.constructor === String && Object.prototype.toString.call(str2) == "[object String]" ) ;   // true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值