网络编程 
首页 > 网络编程 > 浏览文章

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

(编辑:jimmy 日期: 2024/5/8 浏览:3 次 )

前言

如果您关注Airbnb的样式指南,首选方法是使用“String()”"htmlcode">

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'

好吧,我想我们找到了胜利者"color: #ff0000">总结

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

上一篇:vue2配置scss的方法步骤
下一篇:详解vue父子组件关于模态框状态的绑定方案