其中JS有 6 种原始类型:number、string、boolean、null、undefined和Symbol7 种类型object。
原始类型没有自己的属性和方法,但是,类型具有number包装对象,这些对象具有许多预定义的属性和方法,可以简化使用这些数据类型的工作。当访问实际值的方法时,后者可以临时转换为适当的包装对象,如构造函数,或充当具有属性和方法的对象。stringbooleannew String()new Number()new Boolen()
我不明白为什么在直接对值和存储原始值的变量调用方法时都会创建类型string和包装器,但前提是在变量而不是值上调用方法时。booleannumber
例子:
const str = 'hello world'
str.toString() // => "hello world"
'hello world'.toString() // => "hello world"
const bool = true
bool.toString() // => "true"
true.toString() // => "true"
const num = 5
num.toString() // => "5"
5.toString() // => Uncaught SyntaxError: Invalid or unexpected token
问题是其中的所有数字
JS都是浮点数。也就是说,它们可以有小数部分。因此,在表达式中,5.toString()解释器认为点不是方法调用运算符,而是整数和小数部分的分隔符。期望在数字分隔符之后而不是得到他们的解释器并抛出异常。为了在数字上调用包装对象的方法,您需要
取括号中的数字
在方法调用运算符前多加一个点 - 小数部分的分隔符