const res = { state :'200', message: 'success' }
console.log(typeof res.state) // 结果 string
console.log( typeof +res.state) // 结果 number
解释:
在这个例子中,console.log(typeof +res.state) 打印结果为 number,核心原因是 + 运算符将字符串类型的 res.state 转换为了数字类型。
详细拆解:
-
res.state的原始类型:res.state的值是'200'(带引号的字符串),因此typeof res.state输出string。 -
+res.state的作用:这里的+是 一元正号运算符,它的核心功能是将操作数转换为数字类型。当操作数是「纯数字字符串」(如'200')时,+会将其转换为对应的数字(200)。 -
转换后的类型:
+res.state的结果是数字200,因此typeof +res.state输出number。
总结:
+ 运算符在这里强制将字符串类型的 '200' 转换为了数字类型的 200,所以第二次打印的类型是 number。这是 JavaScript 中快速实现「字符串转数字」的常用技巧(尤其适用于确保接口返回的状态码、ID 等字段为数字类型)。

被折叠的 条评论
为什么被折叠?



