字符串转化成数组
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"(模板字符串)
253

被折叠的 条评论
为什么被折叠?



