首页 > 定义一个字符串变量的几种方式的区别?

定义一个字符串变量的几种方式的区别?

通过以下三种方式定义一个字符串,它们之间有什么区别呢?

var str = '';
console.log((typeof str),(str instanceof Object),(str instanceof String))

output: string false false


var str = String('');
console.log((typeof str),(str instanceof Object),(str instanceof String))

output: string false false


var str = new String('');
console.log((typeof str),(str instanceof Object),(str instanceof String))

output: object true true


首先有一点,

在js中,数据类型分为两类:原始类型(primitive type)和对象类型(object type)。

那么我们来看第一种方法

var str = '';

创建的便是原始类型string,所以他的类型是string。
而第三种方法

var str = new String('');

则是使用了构造函数来创建了一个叫做String的对象类型,所以它的类型是对象,也就是Object。
再来看第二种方法

var str = String('');

这则是因为js里有一个函数就叫做String(),作用是把对象的值转换为字符串,所以就会有以上结果。


单独 String('') 其实并不是面向对象形式的写法,你只能把它看做是一个 String 函数,其返回的就是 '' 本身,所以和第一种结果一致。


js中有5种基本数据类型:Undefined.Null.Boolean.Number和String,还有一种复杂数据类型Object。
js的变量是松散类型的,所以可以用来保存以上任一一种数据类型。

接下来看看题主的三代代码~
第一段和第二段,效果其实是一样的创造了一个包含字符串'string'的变量,但是这是2种不同的方法,具体说来第一种是直接赋予初值为字符串。第二种是一种强制类型转换为String的转换函数,底层调用应该也是toString这个字符串对象方法。
第三种也称为实例化一个构造函数 这里String是一个构造函数,所以他实例后会是一个对象即唯一的复杂数据类型Object。
用typeof 检测的时候前2个后第三个是不一样的。

所以当你确定值是字符串用第一种,
当你不确定一个值是什么类型,但是想要强制成String则用第二种,
如果你想得到一个String对象则用第三种,只有在对象上我们才可以添加各种属性与方法。

以上定义来自《javascript高级程序设计》?爬下床 翻了一下确认都没说错 感人 上床 再歇会


Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of Boolean and Numbers.)

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

引用来自于JS API文档的说明
通过''或“”包裹的字符串或不作为构造函数调用String函数创建的字符串都是基本类型的字符串而非对象
也就是typeof返回的是string 而非 object。而当基本类型的字符串调用String对象的方法时,JS引擎会自动将其包装成一个String对象

【热门文章】
【热门文章】