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