数组转字符串方法:
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"]