JavaScript 中的 toString() 函数
大多数 JavaScript 对象和原始值都有一个 toString()
将值转换为字符串的函数。 许多内置方法使用 toString()
在引擎盖下,就像 浏览器的 alert()
功能 。
Primitives
JavaScript 数字原语有一个 toString()
将数字转换为字符串的函数。 这是最常见的用途之一 toString()
:
const num = 42;
num.toString(); // '42'
typeof num.toString(); // 'string'
// Can also use `toString()` on a number literal as long as you
// use parentheses.
(42).toString(); // '42'
所有 原始值 除外 null
和 undefined
有一个 toString()
函数:字符串、数字、布尔值、BigInts 和 符号 。
// String:
'Hello'.toString(); // 'Hello'
// Number:
(42).toString(); // '42'
// Boolean:
true.toString(); // 'true'
// BigInt:
42n.toString(); // '42'
// Symbol:
Symbol('test').toString(); // 'Symbol(test)'
重要的一点是打电话是安全的 toString()
任意 JavaScript 值 ,只要该值不是 null
或者 undefined
,最简单的检查方法是使用 == null
: 最常见的用途 ==
就是它 v == null
是简写 v === null || v === undefined
。
if (v != null) {
// Won't throw an error, unless you wrote a custom `toString()` that throws
v.toString();
}
对象
Object
JavaScript 中的类是所有对象的基类,它有一个简单的 toString()
通常打印的方法 [object Object]
:
// Equivalent to `const obj = {};`
const obj = new Object();
obj.toString(); // '[object Object]'
[object Object]
输出常常让初学者感到困惑,因为他们想看到对象的键和值。 您可以自己遍历对象的键和值,但最简单的一行代码是使用 JSON.stringify()
.
const obj = { name: 'Jean-Luc Picard', rank: 'Captain' };
// '{"name":"Jean-Luc Picard","rank":"Captain"}'
console.log(JSON.stringify(obj));
如果您定义一个 JavaScript 类 ,您可以覆盖 toString()
返回任何你想要的函数:
class MyClass {
toString() {
return 'Hello, World!';
}
}
const obj = new MyClass();
obj.toString(); // 'Hello, World!'
toString()
参数
一些 toString()
函数接受参数,最显着的是数字和 Node.js 缓冲区 。
toString()
JavaScript 数字函数需要一个 radix
定义数字系统基础的参数。 换句话说, num.toString(2)
将数字转换为 二进制数字 字符串, num.toString(10)
将数字转换为以 10 为基数的字符串,并且 num.toString(16)
将数字转换为 十六进制 字符串。
(3).toString(2); // '11'
(42).toString(10); // '42'
(29).toString(16); // '1d'
Node.js 缓冲区 toString()
函数 需要一个 encoding
参数通常是 utf8、hex 或 base64 之一。 这决定了缓冲区中的原始数据是如何编码的。
const fs = require('fs');
const buf = fs.readFileSync('./package.json');
buf.toString('utf8'); // '{ "name": "masteringjs.io", ...}'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

上一篇: JavaScript 中的 null
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论