使用字符串插值时typeof运算符判断变量类型异常的原因咨询
为什么字符串插值后的typeof输出是string而不是原变量类型?
先看你提供的代码:
let num = 1 let st = 'data' console.log(typeof `${num}`, typeof `${st}`)
核心原因
模板字符串的插值语法${}会自动把内部的表达式结果转换成字符串,不管原变量是什么类型。
- 当你写
${num}时,JavaScript会把num(值为1,类型为number)转换成字符串"1",再嵌入到模板字符串中。所以typeof${num}``实际上是在检测这个转换后的字符串的类型,结果自然是string。 - 而
typeof num是直接检测原变量num的类型,它本身就是number,所以输出number。
再举个例子验证:
let bool = true; console.log(typeof bool); // 输出 "boolean" console.log(typeof `${bool}`); // 输出 "string"
这里${bool}被转成了字符串"true",所以类型检测结果为string。
简单说:模板字符串插值出来的是转换后的字符串值,不是原变量本身,typeof检测的是这个新值的类型。
内容的提问来源于stack exchange,提问作者Izza Ijaz
相关产品推荐
相关产品推荐

