「译」在JavaScript中将值转换为字符串的5种方法

原文: 5 Ways to Convert a Value to String in JavaScriptjavascript

若是您关注Airbnb的样式指南,首选方法是使用 “String()”👍

它也是我使用的那个,由于它是最明确的 - 让其余人轻松地遵循你的代码的意图🤓java

请记住,最好的代码不必定是最聪明的方式,它是最能将代码理解传达给他人的代码💯bash

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'
// ⚠️
symbolValue + ''; // ❌ TypeError
复制代码

从这里,您能够看到若是值为一个Symbol ,此方法将抛出TypeError。不然,一切看起来都不错。测试

模板字符串

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

使用模版字符串的结果与结合空字符串的结果基本相同。一样,这可能不是理想的处理方式,由于Symbol它会抛出一个TypeErrorspa

若是你很好奇,那就是TypeError: TypeError: Cannot convert a Symbol value to a string3d

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将值转换为字符串。并且这里真的没有强制发生。所以,您了解可用的全部工具。而后你能够决定使用什么工具而不是根据具体状况使用👍code

有一点我想指出,由于你可能没有注意它。当您在实际string值上使用它时,它会将其更改成带引号的字符串。cdn

.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
复制代码

因此PK其实就是在toString()String(),当你想把一个值转换为字符串。除了它会为undefinednull抛出一个错误,其余表现都很好。因此必定要注意这一点。blog

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()处理nullundefined至关不错。不会抛出任何错误 - 除非这是你想要的。通常来讲记住个人建议。您将最了解您的应用程序,所以您应该选择最适合您状况的方式。

结论:String()🏆

在向您展现了全部不一样方法如何处理不一样类型的值以后。但愿您了解这些差别,而且您将知道下次处理代码时要使用的工具。若是你不肯定,String()老是一个很好的默认选择👍

相关文章
相关标签/搜索