当我听说字符串是 JS 中的原语时,我总是感到困惑,因为每个人都知道字符串有不同的方法,如:length、indexOf、search 等。
let string = "Please locate where 'locate' occurs!";
let pos = str.lastIndexOf("locate");
let position = str.search("locate");
最佳答案
的确,JavaScript 中的一切都像对象一样,因为我们可以在其上调用方法。当我们对字符串使用 new
关键字时,它变成一个对象,否则它是原始类型。
console.log(typeof new String('str')); //object
console.log(typeof 'str'); //string
现在,每当我们尝试访问字符串的任何属性时,它都会使用 new String()
'str'.indexOf('s')
相当于
(new String(str)).indexOf('s').
上述过程称为“装箱”。 “装箱”是将对象包装在原始值周围。
关于javascript - 我们可以说 String 是 Javascript 中的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57873685/