鱼C论坛

 找回密码
 立即注册
查看: 86|回复: 0

[速查宝典] String() -- 将各种类型的值转换为字符串类型

[复制链接]
发表于 2024-7-7 19:03:09 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
String() -- 将各种类型的值转换为字符串类型


函数概述

String() 函数用于将其参数转换为字符串。

它可以将任何类型的值转换为字符串,无论是数字、布尔值、对象还是其他类型。


函数语法
String(value);

参数解析

参数 含义
value 任意类型的值,可以是数字、布尔值、对象、数组、null、undefined 等。


返回值

返回转换后的字符串。

如果参数为 null 或 undefined,返回 "null" 或 "undefined"。


基本用法
// 数字转换为字符串
console.log(String(123)); // 输出 "123"

// 布尔值转换为字符串
console.log(String(true)); // 输出 "true"
console.log(String(false)); // 输出 "false"

// 对象转换为字符串
console.log(String({ key: 'value' })); // 输出 "[object Object]"

// 数组转换为字符串
console.log(String([1, 2, 3])); // 输出 "1,2,3"

// null 和 undefined 转换为字符串
console.log(String(null)); // 输出 "null"
console.log(String(undefined)); // 输出 "undefined"

// 使用 String 对象创建字符串
let strObj = new String(123);
console.log(strObj); // 输出 [String: '123']
console.log(typeof strObj); // 输出 "object"
console.log(strObj.toString()); // 输出 "123"

注意事项

与 toString() 的区别:

String() 与对象的 toString() 方法有相似之处,但也有不同之处。

String() 可以处理 null 和 undefined,而 toString() 在这些情况下会抛出错误。
console.log(String(null)); // 输出 "null"
console.log(String(undefined)); // 输出 "undefined"

// console.log(null.toString()); // 会抛出 TypeError: Cannot read properties of null
// console.log(undefined.toString()); // 会抛出 TypeError: Cannot read properties of undefined
数组的字符串化:

当将数组转换为字符串时,数组元素会用逗号分隔。
console.log(String([1, 2, 3])); // 输出 "1,2,3"
对象的字符串化:

对象转换为字符串时,返回的是 "[object Object]"。

要获得对象的自定义字符串表示,可以重写对象的 toString() 方法。
let obj = { key: 'value' };
console.log(String(obj)); // 输出 "[object Object]"

obj.toString = function() {
    return `Key is ${this.key}`;
};
console.log(String(obj)); // 输出 "Key is value"

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-18 16:38

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表