如何在Javascript中获取字符串的原始值?

在JavaScript中,有5种原始类型:undefined,null,boolean,string和number。其他一切都是对象。

原始类型boolean,string和number可以由其包装对象包装,即分别为Boolean,String和Number构造函数的实例。

为了从对象包装器中获取原始值,我们需要在对象上调用valueOf方法。

示例

console.log(typeof true);
console.log(typeof new Boolean(true));
console.log(typeof (new Boolean(true)).valueOf());
console.log(typeof "abc");
console.log(typeof new String("abc"));
console.log(typeof (new String("abc")).valueOf());
console.log(typeof 123);
console.log(typeof new Number(123));
console.log(typeof (new Number(123)).valueOf());

输出结果

"boolean"
"object"
"boolean"
"string"
"object"
"string"
"number"
"object"
"number"

如您所见,原语的类型为布尔值,字符串或数字,而其包装器为对象。一旦使用valueOf获得值,我们就会再次获得基元。

但是,基元在JS中也具有属性。这是因为JavaScript根据需要在原语和对象之间强制转换。因此,如果我们访问此基元上的length属性,则将其包装在一个对象中,将访问此属性,然后再次解开基元。