js str字符串和arr数组互相转换

js str字符串和arr数组互相转换

字符串转为数组

1、split()方法
返回的是原字符串的数组

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

2、Array.from()方法
返回一个新的数组实例

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

3、扩展运算符(…)

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

4、for...of循环:

var str = "hello";  
var arr = [];  
for (let i of str) {  
  arr.push(i);  
}  
console.log(arr); // 输出:["h", "e", "l", "l", "o"]

5、Array.prototype.map()方法
可以通过回调函数对每个元素进行操作,适用于需要对字符串进行转换的情况

var str = "hello";  
var arr = Array.prototype.map.call(str, function (i) {  
  return i;  
});  
console.log(arr); // 输出:["h", "e", "l", "l", "o"]

数组转为字符串

1、join()方法

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

2、toString()方法
只能使用逗号作为分隔符,如果需要按照其他方式连接数组中的元素,需要用其他方法。

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

3、扩展运算符(…)和字符串的+操作符

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

4、Array.prototype.reduce()方法和字符串的+操作符
可以自定义连接方式,通过回调函数对每个元素进行操作

var arr = ["h", "e", "l","l","o"];  
var str = arr.reduce((acc, val) => acc + val, "");  
console.log(str); // 输出:hello

5、Array.prototype.map()方法和字符串的join()方法
可以使用指定的分隔符连接数组元素

var arr = ["h", "e", "l","l","o"];  
var str = arr.map(item => item).join("");  
console.log(str); // 输出:hello

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值