Home >Web Front-end >JS Tutorial >Analysis of the method of converting a value into a string in JavaScript [Translation]_javascript skills

Analysis of the method of converting a value into a string in JavaScript [Translation]_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:49:43969browse

译者注:前两天在看ES5的时候顺便出了一道题,今天看到这篇文章,刚好解释的很清楚,就翻译了一下.
在JavaScript中,主要有三种方法能让任意值转换为字符串.本文讲解了每种方法以及各自的优缺点.

1.转换字符串的三种方法
这三种将value转换为字符串的方法是:

1.value.toString()
2."" + value
3.String(value)

第一种方法存在的问题是,它不能把null和undefined转换为字符串.还有第二种和第三种方法,这两种方法的效果基本一样.

•""+value: 使用加法运算符配合一个空字符串可以把任意值转换为字符串,我觉得这种方法代码的可读性很差,但相对String(value)来,还是有一些人更喜欢用这种转换方式.
•String(value): 这种方法可读性更好,唯一的问题是,这种函数调用可能会迷惑一些人,尤其是那些熟悉Java的的程序员,因为String同时也是一个构造函数.要注意的是它作为普通函数和作为构造函数时的表现完全不同:

复制代码 代码如下:

> String("abc") === new String("abc")
false

> typeof String("abc")
'string'
> String("abc") instanceof String
false

> typeof new String("abc")
'object'
> new String("abc") instanceof String
true


String作为普通函数时会产生一个字符串(一个原始值).作为构造函数时会产生一个String对象的实例.后者在JavaScript中很少用到,所以基本上你可以忽略掉String作为构造函数的用法,但一定要记得它是个转换函数.

2.""+value 和 String(value)的细微差别
到现在你已经知道了+ 和 String()都可以将它们的“参数”转换为字符串.但他们的转换方式还是着有细微的差别,不过几乎所有的情况下,转换结果都是一样的.

2.1 将原始值转换为字符串
这两种方法都是使用引擎内部的ToString()操作将原始值转换为字符串的.“内部操作”的意思是:这个操作函数是在ECMAScript 5.1 (§9.8)中定义的,但ES语言本身并不能访问到它.下面这个表格解释了ToString()是如何转换原始值的.

参数 结果
undefined "undefined"
null "null"
布尔值 "true"或者"false"
数字 数字作为字符串,比如"1.765"
字符串 无需转换

2.2 Convert object value to string

Both methods first convert the object value to a primitive value, and then convert the primitive value to a string. But in this During conversion, the internal ToPrimitive(Number) operation is used (unless the date object is converted), while String() uses ToPrimitive(String).

•ToPrimitive(Number): Convert an object to To convert a value to a primitive value, first call obj.valueOf(). If the return value is a primitive value, return the primitive value. If not, call obj.toString() again. If the return value is a primitive value, return the primitive value. value. Otherwise, a TypeError exception is thrown.
•ToPrimitive(String): Similar to the above method, except that the obj.toString() method is called first instead of obj.valueOf().
By converting the following object , you can see the difference between them:
Copy the code The code is as follows:

var obj = {
valueOf: function () {
console.log("valueOf");
return {}; // Not the original value, continue executing
},
toString: function () {
console.log("toString");
return {}; // Not the original value, continue execution
}
};

//Run:
> "" obj
valueOf
toString
TypeError: Cannot convert object to primitive value

> String(obj)
toString
valueOf
TypeError : Cannot convert object to primitive value

2.3 The results are usually the same
The differences mentioned above are almost impossible to encounter in actual situations. Because: Most of them Objects all use the default inherited valueOf() method, and the return value is always the object itself.

Copy code The code is as follows:

> var x = {}
> x.valueOf() === x
true


Therefore, ToPrimitive(Number) usually skips the valueOf method and returns the return value of the toString() method, which behaves exactly the same as ToPrimitive(String). However, if this object is an object instance of Boolean, Number or String, then Its valueOf() will return a primitive value (the original value before being wrapped by this object). Then these two operations will be performed as follows:

•ToPrimitive(Number) returns the object's valueOf( ) method's return value (the original value before being wrapped) and the result after the ToString() operation.
•ToPrimitive(String) returns the return value of the object's toString() method (the object's original value before being wrapped) The return value of the ToString() operation on the original value).
In this way, they still return the same result, but the conversion method is different.

3. Conclusion

Which method should you choose to convert other types of values ​​​​to strings? If you can ensure that the value will never be null or undefined, you can use value.toString() to convert. Otherwise," "You can choose either value or String(value). It depends on personal preference. I think String(value) is more clear.

4. Related articles

  1. JavaScript values: not everything is an object [The difference between primitive values ​​and object values]
  2. What is {} {} in JavaScript? [Explained how operators work]
  3. String concatenation in JavaScript [How to better concatenate multiple strings]
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn