在JavaScript中将值转换为字符串
Converting values to strings in JavaScript is more complicated than it might seem:
在 JavaScript 中将值转换为字符串比看起来要复杂:
- Most approaches have values they can’t handle.
- 大多数方法都有无法处理的值。
- We don’t always see all of the data.
- 我们并不总是能看到所有数据。
Converting values to strings #
将值转换为字符串 #
Example: code that is problematic #
示例:有问题的代码 #
Can you spot the problem in the following code?
你能在以下代码中发现问题吗?
class UnexpectedValueError extends Error { constructor(value) { super('Unexpected value: ' + value);
}
}
For some values, this code throws an exception in line A:
对于某些值,这段代码在 A 行抛出异常:
new UnexpectedValueError(Symbol())
TypeError: Cannot convert a Symbol value to a string new UnexpectedValueError({__proto__:null})
TypeError: Cannot convert object to primitive value
Read on for more information.
继续阅读以获取更多信息。
Five ways of converting values to strings #
将值转换为字符串的五种方法 #
These are five common ways of converting a value v to string:
这五种将值 v 转换为字符串的常见方法:
-
String(v) -
String(v) -
'' + v -
'' + v -
`${v}` -
`${v}` -
v.toString() -
v.toString() -
{}.toString.call(v) -
{}.toString.call(v)
Which of these should we use? Let’s first check how they fare with the following tricky values:
我们应该使用哪一个?让我们先检查它们在以下棘手值上的表现:
-
undefined -
undefined -
null -
null -
Symbol() -
Symbol() -
{__proto__: null} -
{__proto__: null}
These are the results:
这些是结果:
undefined |
null |
Symbol() |
{__proto__:null} |
|
|---|---|---|---|---|
String(v) |
✔ | ✔ | ✔ | TypeError |
'' + v |
✔ | ✔ | TypeError |
TypeError |
`${v}` |
✔ | ✔ | TypeError |
TypeError |
v.toString() |
TypeError |
TypeError |
✔ | TypeError |
{}.toString.call(v) |
✔ | ✔ | ✔ | ✔ |
undefined |
null |
Symbol() |
{__proto__:null} |
|
|---|---|---|---|---|
String(v) |
✔ | ✔ | ✔ | TypeError |
'' + v |
✔ | ✔ | TypeError |
TypeError |
`${v}` |
✔ | ✔ | TypeError |
TypeError |
v.toString() |
TypeError |
TypeError |
✔ | TypeError |
{}.toString.call(v) |
✔ | ✔ | ✔ | ✔ |
Conclusions:
结论:
- Among the five approaches listed in the table only
{}.toString.call(v)works for all tricky values. - 在表中列出的五种方法中,只有
{}.toString.call(v)对所有棘手的值都有效。 - If we don’t need to be 100% safe and would like to be less verbose then
String(v)is also a good solution. - 如果我们不需要 100% 安...