欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-01-10 08:01:14
前言 如果您关注airbnb的样式指南,首选方法是使用“string()”???? 它也是我使用的那个,因为它是最明确的 - 让其他人轻松地遵循你的代码的...

前言

如果您关注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'
// ⚠️
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: 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

因此,您通常不会使用json.stringify将值转换为字符串。而且这里真的没有强制发生。因此,您了解可用的所有工具。然后你可以决定使用什么工具而不是根据具体情况使用????

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

.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(),当你想把一个值转换为字符串。除了它会为undefined和null抛出一个错误,其他表现都很好。所以一定要注意这一点。

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()总是一个很好的默认选择????

总结

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