0
点赞
收藏
分享

微信扫一扫

前端JS数组问题: 数组去重, 字符串分割成数组, 数组拼接成字符串

敬亭阁主 2022-04-18 阅读 160

1. 数组去重:

  let arr1 = ['张三','李四','王五','李四','赵六','张三'];
  let arr2 = Array.from(new Set(arr1));
  console.log(arr2)

输出结果:

 ['张三', '李四', '王五', '赵六']


2. 字符串分割成数组

  let str1 = "张三,李四,王五,李四,赵六,张三";
  let arr1 = str1.split(",");
  console.log(arr1)

  console.log("-----")

  let arr2 = str1.split(",",2)
  console.log(arr2)
  

输出结果:

['张三', '李四', '王五', '李四', '赵六', '张三']
-----
['张三', '李四']


3. 数组拼接成字符串

  let arr1=['张三','李四','王五','李四','赵六','张三'];
  let str1 = arr1.join()
  console.log(str1)

  console.log("-----")

  let str2 = arr1.join("")
  console.log(str2)

输出结果:

张三,李四,王五,李四,赵六,张三
-----
张三李四王五李四赵六张三



综合使用:

1.名单字符串去重

  let str1 = "张三,李四,王五,李四,赵六,张三";
  let str2 = Array.from(new Set(str1.split(","))).join()
  console.log(str2)

输出结果:

张三,李四,王五,赵六
举报

相关推荐

0 条评论