JavaScript 中将值转换为字符串的 5 种方法

2025-06-10

JavaScript 中将值转换为字符串的 5 种方法

SamanthaMing.com 的 CodeTidbit

如果您遵循 Airbnb 的样式指南,则首选方法是使用“String()”👍

这也是我使用的,因为它是最明确的 - 使其他人可以轻松理解代码的意图🤓

记住,最好的代码不一定是最聪明的方式,而是能最好地向他人传达你的代码理解的方式。

const value = 12345;

// Concat Empty String
value + '';

// Template Strings
`${value}`;

// JSON.stringify
JSON.stringify(value);

// toString()
value.toString();

// String()
String(value);

// RESULT
// '12345'
Enter fullscreen mode Exit fullscreen mode

比较 5 种方法

好了,我们用不同的值来测试这 5 种方法。以下是我们要测试的变量:

const string = "hello";
const number = 123;
const boolean = true;
const array = [1, "2", 3];
const object = {one: 1 };
const symbolValue = Symbol('123');
const undefinedValue = undefined;
const nullValue = null;
Enter fullscreen mode Exit fullscreen mode

连接空字符串

string + ''; // 'hello'
number + ''; // '123'
boolean + ''; // 'true'
array + ''; // '1,2,3'
object + ''; // '[object Object]'
undefinedValue + ''; // 'undefined'
nullValue + ''; // 'null'

// ⚠️
symbolValue + ''; // ❌ TypeError
Enter fullscreen mode Exit fullscreen mode

从这里可以看出,TypeError如果值为 a ,此方法将抛出一个异常Symbol。除此之外,一切看起来都很好。

模板字符串

`${string}`; // 'hello'
`${number}`; // '123'
`${boolean}`; // 'true'
`${array}`; // '1,2,3'
`${object}`; // '[object Object]'
`${undefinedValue}`; // 'undefined'
`${nullValue}`; // 'null'

// ⚠️
`${symbolValue}`; // ❌ TypeError
Enter fullscreen mode Exit fullscreen mode

使用模板字符串的结果本质上与Concat 空字符串相同。同样,这可能不是处理时的理想方法,Symbol因为它会抛出一个TypeError

如果你好奇的话,这是 TypeError:TypeError: Cannot convert a Symbol value to a string

JSON.stringify()

// ⚠️
JSON.stringify(string); // '"hello"'
JSON.stringify(number); // '123'
JSON.stringify(boolean); // 'true'
JSON.stringify(array); // '[1,"2",3]'
JSON.stringify(object); // '{"one":1}'
JSON.stringify(nullValue); // 'null'
JSON.stringify(symbolValue); // undefined
JSON.stringify(undefinedValue); // undefined
Enter fullscreen mode Exit fullscreen mode

所以你通常不会使用 JSON.stringify 将值转换为字符串。这里实际上没有强制转换。我主要是为了完整起见才包含这种方式。这样你就能了解所有可用的工具。然后你可以根据具体情况决定使用什么工具或不使用什么工具👍

我想指出一点,因为你可能没有注意到。当你将它用于实际值时,它会将其更改为带引号string的字符串

您可以在 Kyle Simpson 的“你不知道的 JS 系列”中阅读更多相关内容:
JSON 字符串化

附注:了解基本原理的重要性!

是的,你可能注意到了,在我的代码笔记里,我经常引用 Kyle 的书。说实话,我学到了很多。由于我没有计算机科学背景,很多基础概念我都欠缺。他的书让我意识到理解基础知识的重要性。对于那些想成为认真程序员的人来说,提升水平的关键在于真正理解基础知识。没有基础知识,很难提升。你最终只能猜测问题所在。但如果你了解了基础知识,你就能理解某件事的“为什么”。而了解“为什么”能帮助你更好地执行“怎么做”。总之,强烈推荐这一系列书籍给那些想成为高级程序员的人!

到字符串()

string.toString(); // 'hello'
number.toString(); // '123'
boolean.toString(); // 'true'
array.toString(); // '1,2,3'
object.toString(); // '[object Object]'
symbolValue.toString(); // 'Symbol(123)'

// ⚠️
undefinedValue.toString(); // ❌ TypeError
nullValue.toString(); // ❌ TypeError
Enter fullscreen mode Exit fullscreen mode

所以,当你想把一个值转换成字符串时,真正的关键在于toString()and 。这个方法做得很好。只是它会抛出一个错误所以一定要注意这一点。String()undefinednull

细绳()

String(string); // 'hello'
String(number); // '123'
String(boolean); // 'true'
String(array); // '1,2,3'
String(object); // '[object Object]'
String(symbolValue); // 'Symbol(123)'
String(undefinedValue); // 'undefined'
String(nullValue); // 'null'
Enter fullscreen mode Exit fullscreen mode

好吧,我想我们找到了赢家🏆

如您所见,它String()处理nullundefined很好。没有抛出任何错误——除非您不希望出现这种情况。请记住,我的建议只是一般而言。您最了解您的应用,因此您应该根据自己的情况选择最合适的方法。

结论:String()

在向您展示了所有不同的方法如何处理不同类型的值之后,希望您能够意识到这些差异,并知道下次处理代码时应该选择哪种工具。如果您不确定,String()始终使用默认工具 👍

社区意见

@MaxStalker我会根据应用程序使用不同的方法:

  • “”+ val:简单地将数字转换为字符串 - 比如在 .map() 内部
  • JSON.stringify(val):需要转换小型非嵌套对象
  • .toString(radix):将数字转换为十六进制或二进制

@frontendr :使用 JSON.stringify 时要小心,它会将字符串转换为带引号的字符串 😉

@super.pro.dev我也知道:new String(foo),但我不喜欢这种方法(它将创建一个 String 对象,与创建字符串原语的 String(没有“new”)相反)

资源


感谢阅读❤
打个招呼!Instagram | Twitter | Facebook | Medium |博客

鏂囩珷鏉ユ簮锛�https://dev.to/samanthaming/5-ways-to-convert-a-value-to-string-in-javascript-5877
PREV
使用 VuePress 构建我的新网站
NEXT
在 JavaScript 中设置默认值的 3 种方法