JavaScript 中的 toString() 函数

发布于 2022-11-21 22:01:12 字数 3734 浏览 131 评论 0

大多数 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

雾里花

暂无简介

文章
评论
27 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文