如题你是怎么想的呢? 这个很简单啊, typeof 一下, 再判断 length.
- if(typeof unknownVariable ==='string' && unknownVariable.length){
- ...
- }
复制代码
搞定了吗?
如果这个字符串是用 new String() 创建的会如何呢? typeof 这个未知变量肯定是 object. 你会怎么办? 你肯定还得先判断类型, typeof unknownVariable==='object' ? 但你得想还有一个 null 变量的 typeof 值也是 object. 那是不是还得 && unknownVariable 一下? 现在就是一个非空对象了, 接着要不要判断一下 length? 应该不用了. 但最后 typeof 是 object 的不一定是字符串对象啊, 可以是别的对象, 如数组, json 对象, new 出来的别的对象等等. 要怎么办呢?
这就要上一个很少用到但有用的方法了: valueOf.
valueOf 会以变量原始类型的形式进行输出.
- let str1="test"
- let str2=new String('test2')
- let arr1=[1,2,3]
- let fn1=function(){
- console.log('this is a function')
- }
- let obj1={
- name:'gpd'
- }
- let obj2=new Object()
- obj2.name='gpd'
- str1.valueOf() // "test"
- str2.valueOf() //"test2"
- arr1.valueOf() //[1,2,3]
- fn1.valueOf() //fn1(){}
- obj1.valueOf() // {name:"gpd"}
- obj2.valueOf() // {name:"gpd"}
复制代码
所以, 无论你是字符串字面量还是 new String 得到的一个字符串对象, 它的 valueOf 值都是一个字符串字面量. 然后, 它的 typeof 值都是 string .
所以最后的判断的是
- if(typeof unknownVariable !=undefined
- && unknownVariable
- && typeof unknowVariable.valueOf() === "string")
- {
- ...
- }
复制代码
来源: https://juejin.im/post/5b715182e51d4566757e150e