首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >JS 字符串和数组相互转换

JS 字符串和数组相互转换

作者头像
很酷的站长
发布2022-12-04 15:40:16
发布2022-12-04 15:40:16
3.3K0
举报
1. 字符串转为数组

使用字符串对象的 split() 方法可以将字符串转为数组,语法格式:

separator: 分割符 limit: 返回的数组最大长度

代码语言:javascript
复制
String.split(separator, limit)

当省略所有参数时,不进行分割字符串,将字符串整体放到数组中返回

代码语言:javascript
复制
const arr = 'hello world'.split()console.log(arr);//['hello world']

指定分割符将字符串切割为数组

代码语言:javascript
复制
const string = 'hello world !'const array = string.split(' ')console.log(array)// ['hello', 'world', '!']

省略第二个参数时,会尽量多的分割字符串,可以指定分割后得到的数组最多有几个元素

代码语言:javascript
复制
const lang = 'html,css,js,vue'const array = lang.split(',', 2)console.log(array)// ['html', 'css']
2. 数组转为字符串

Array.toString()

数组转为字符串可以使用 toString 方法,但是这个方法不能自定义分割符,默认分割符为英文逗号 ,

代码语言:javascript
复制
const lang = ['html', 'css', 'js', 'vue']const string = lang.toString()console.log(string) //html,css,js,vue

Array.join()

使用数组方法 join() 将数组转为字符串可以自定义分割符

省略分割符时默认使用英文逗号作为分割符,当分割符为空字符串时代表没有分割符

代码语言:javascript
复制
const lang = ['html', 'css', 'js', 'vue']let string = lang.join()console.log(string) //html,css,js,vuestring = lang.join('')console.log(string) // htmlcssjsvue
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 字符串转为数组
  • 2. 数组转为字符串
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档