字符串转换成数组 的方法

1. split()方法

  • 通过空字符串作为分隔符
    const info = "字符串abc123";const arr = info.split('');console.log(arr);// ["字", "符", "串", "a", "b", "c", "1", "2", "3"]
  • 通过符号作为分隔符
    const info = "字,符串,ab,c12,3";const arr = info.split(',');console.log(arr);// ["字", "符串", "ab", "c12", "3"]

2. Array.from

  • 将一个类数组对象(有length属性的对象)或者可遍历对象转换成一个真正的数组
    const info = "字符串abc456";const arr = Array.from(info)console.log(arr);// ["字", "符", "串", "a", "b", "c", "4", "5", "6"]

3.  展开运算符

  • 展开运算符(...) 允许在需要多个元素(如数组文字)的地方扩展诸如字符串之类的可迭代对象。
    const info = "字符串abc789";const arr = [ ...info ]console.log(arr);// ["字", "符", "串", "a", "b", "c", "7", "8", "9"]

      

        

本文链接:https://my.lmcjl.com/post/10378.html

展开阅读全文

4 评论

留下您的评论.