JavaScript中字符串和数组如何相互转化

字符串转化成数组

1. split() 方法

将字符串按指定的分隔符拆分成数组。如果不传参数,则返回包含整个字符串的数组。

const str = "hello";
const arr1 = str.split("");  // 按空字符串分割 -> ["h", "e", "l", "l", "o"]
const arr2 = str.split();    // 不传参数 -> ["hello"]
const arr3 = "a,b,c".split(","); // 按逗号分割 -> ["a", "b", "c"]

2. Array.from() 方法

直接从一个可迭代对象(如字符串)创建数组。

const str = "hello";
const arr = Array.from(str);  // ["h", "e", "l", "l", "o"]

3. 扩展运算符 [...str]

利用 ES6 的扩展运算符将字符串展开成数组。

const str = "hello";
const arr = [...str];  // ["h", "e", "l", "l", "o"]

4. Object.assign([], str)

将字符串的字符复制到数组中(较少使用)。

const str = "hello";
const arr = Object.assign([], str);  // ["h", "e", "l", "l", "o"]

5. Array.prototype.slice.call(str)

借用数组的 slice 方法转换字符串(较旧的写法)。

const str = "hello";
const arr = Array.prototype.slice.call(str);  // ["h", "e", "l", "l", "o"]

6. match() + 正则表达式

使用正则匹配每个字符(适用于更复杂的分割情况)。

const str = "hello";
const arr = str.match(/./g);  // ["h", "e", "l", "l", "o"]

数组转化成字符串

1. join() 方法

最常用,将数组元素按指定分隔符连接成字符串。

const arr = ['a', 'b', 'c'];
const str1 = arr.join();      // 默认用逗号分隔 -> "a,b,c"
const str2 = arr.join('');    // 无分隔符 -> "abc"

2. toString() 方法

将数组直接转为逗号分隔的字符串(无法自定义分隔符)。

const arr = [1, 2, 3];
const str = arr.toString();  // "1,2,3"

3.模板字符串

直接强制类型转换或拼接。

const arr = [1, 2, 3];
const str2 = `${arr}`;          // "1,2,3"(模板字符串)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值