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

(编辑:jimmy 日期: 2024/9/23 浏览:2)

如果您关注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'

比较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;

结合空字符串

string + ''; // 'hello'
number + ''; // '123'
boolean + ''; // 'true'
array + ''; // '1,2,3'
object + ''; // '[object Object]'
undefinedValue + ''; // 'undefined'
nullValue + ''; // 'null'
// "htmlcode">
`${string}`; // 'hello'
`${number}`; // '123'
`${boolean}`; // 'true'
`${array}`; // '1,2,3'
`${object}`; // '[object Object]'
`${undefinedValue}`; // 'undefined'
`${nullValue}`; // 'null'
// "htmlcode">
// "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将值转换为字符串。而且这里真的没有强制发生。因此,您了解可用的所有工具。然后你可以决定使用什么工具而不是根据具体情况使用"htmlcode">

string.toString(); // 'hello'
number.toString(); // '123'
boolean.toString(); // 'true'
array.toString(); // '1,2,3'
object.toString(); // '[object Object]'
symbolValue.toString(); // 'Symbol(123)'
// "htmlcode">
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()总是一个很好的默认选择

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。