JS数组转字符串方法和字符串转数组方法

数组转字符串方法:

1. toString()
toString() 方法将数组转换为一个逗号分隔的字符串。

const arr = [1, 2, 3, 4];
const str = arr.toString();
console.log(str); // 输出 "1,2,3,4"

2. join(separator)
join() 方法可以将数组的所有元素连接成一个字符串,并且可以指定一个分隔符。

const arr = [1, 2, 3, 4];
const str = arr.join('-');
console.log(str); // 输出 "1-2-3-4"

如果不指定分隔符,join() 会默认使用逗号 , 作为分隔符。
3. 使用 JSON.stringify()
JSON.stringify() 可以将数组转换为 JSON 格式的字符串。

const arr = [1, 2, 3, 4];
const str = JSON.stringify(arr);
console.log(str); // 输出 "[1,2,3,4]"

4. 使用 Array.prototype.reduce()
reduce() 方法可以通过累加器的方式将数组元素逐一连接成字符串。

const arr = [1, 2, 3, 4];
const str = arr.reduce((acc, curr) => acc + curr.toString(), "");
console.log(str); // 输出 "1234"

字符串转数组方法:

1. split()
split() 是最常用的方法,它根据指定的分隔符将字符串拆分成数组。

const str = "apple,banana,orange";
const arr = str.split(',');
console.log(arr); // 输出 ["apple", "banana", "orange"]

如果不指定分隔符,split() 会将整个字符串作为一个数组的唯一元素。

const str = "hello";
const arr = str.split();
console.log(arr); // 输出 ["hello"]

2. 使用 Array.from()
Array.from() 可以将字符串的每个字符转为数组的一个元素。

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

3. 使用扩展运算符 …
扩展运算符可以将字符串中的每个字符展开为数组的元素。

const str = "hello";
const arr = [...str];
console.log(arr); // 输出 ["h", "e", "l", "l", "o"]

4. 使用 match()
match() 方法可以使用正则表达式从字符串中提取出匹配的部分,形成一个数组。

const str = "apple, banana; orange";
const arr = str.match(/\w+/g);
console.log(arr); // 输出 ["apple", "banana", "orange"]
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值