JavaScript中将值转换为字符串的五种方法总结

作者:桌面漫游时间:2026-10-23 08:02:33浏览:322

本文对比了JavaScript中将值转换为字符串的五种常用方法:拼接空字符串、模板字符串、JSON.stringify、toString()以及String()。通过测试不同数据类型,发现String()在处理null和undefined时最为安全且表现一致,是推荐的默认转换方式。

前言与Airbnb规范推荐

前言

如果您关注Airbnb的JavaScript代码规范,首选的方法是使用String()构造函数。

这也是我推荐的方式,因为它意图最明确,能让其他开发者轻松理解代码的转换目的。

请记住,优秀的代码不一定是最巧妙的,而是最能清晰传达意图的代码。


const value = 12345;
// Concat Empty String
value + '';
// Template Strings
`${value}`;
// JSON.stringify
JSON.stringify(value);
// toString()
value.toString();
// String()
String(value);
// RESULT
// '12345'

五种转换方法的对比测试

五种方法的对比

接下来,我们将使用不同的数据类型来测试这五种转换方式。以下是测试所用的变量定义:


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;

与空字符串拼接

与空字符串拼接


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

从测试结果可以看出,如果值为Symbol类型,此方法会抛出TypeError。除此之外,其他类型的转换结果均符合预期。

模板字符串

模板字符串


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

使用模板字符串的结果与拼接空字符串基本一致。同样,这种方法在处理Symbol类型时也不是理想选择,因为它会抛出TypeError。

具体的错误信息为:TypeError: Cannot convert a Symbol value to a string。

JSON.stringify方法

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

通常情况下,我们不会使用JSON.stringify()来将普通值转换为字符串,因为这里并没有强制的转换行为发生。了解所有可用工具后,您可以根据具体场景选择最合适的方案。

有一点值得注意,您可能未曾察觉:当对已有的字符串值使用该方法时,它会将结果转换为带引号的字符串形式。

toString()方法

.toString()


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

实际上,在将值转换为字符串时,主要的竞争者是toString()和String()。除了toString()会对undefined和null抛出错误外,其他类型的表现都良好。因此,使用时需特别注意这一点。

String()构造函数

String()


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'

看来我们找到了获胜者。

如您所见,String()能很好地处理null和undefined值,不会抛出任何错误(除非这是您期望的行为)。一般而言,请牢记我的建议:您最了解您的应用程序,因此应选择最适合您具体情况的方式。

结论与建议

结论:String()是首选

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

总结

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对本站的支持。

作者最新文章