JS 字符串和数组相互转换
2024-10-03
17
1. 字符串转为数组
使用字符串对象的 split()
方法可以将字符串转为数组,语法格式:
separator: 分割符 limit: 返回的数组最大长度
String.split(separator, limit)
当省略所有参数时,不进行分割字符串,将字符串整体放到数组中返回
const arr = 'hello world'.split()console.log(arr);//['hello world']
指定分割符将字符串切割为数组
const string = 'hello world !'const array = string.split(' ')console.log(array)// ['hello', 'world', '!']
省略第二个参数时,会尽量多的分割字符串,可以指定分割后得到的数组最多有几个元素
const lang = 'html,css,js,vue'const array = lang.split(',', 2)console.log(array)// ['html', 'css']
2. 数组转为字符串
Array.toString()
数组转为字符串可以使用 toString
方法,但是这个方法不能自定义分割符,默认分割符为英文逗号 ,
const lang = ['html', 'css', 'js', 'vue']const string = lang.toString()console.log(string) //html,css,js,vue
Array.join()
使用数组方法 join()
将数组转为字符串可以自定义分割符
省略分割符时默认使用英文逗号作为分割符,当分割符为空字符串时代表没有分割符
const lang = ['html', 'css', 'js', 'vue']let string = lang.join()console.log(string) //html,css,js,vuestring = lang.join('')console.log(string) // htmlcssjsvue
更新于:15天前赞一波!
相关文章
- 【说站】python列表如何结合数组使用
- 【说站】python使用f格式化字符串
- 【说站】python str.zfill填充字符串
- 【说站】python中str()函数转换字符串
- 【说站】php数组转json字符串
- 【说站】php数组合并的方法
- 【说站】php数组排序算法
- 【说站】php数组实现原理
- 【说站】php数组添加元素
- 【说站】python字符串如何简单运算
- 【说站】python字符串格式化的方法整理
- 【说站】python字符串如何取值
- 【说站】php数组赋值方式
- 【说站】php数组交集函数
- JS 的 apply 方法
- JS 数组去重的多种方法
- JS 函数中的 arguments 类数组对象
- 介绍Js简单的递归排列组合
- Node.js 软件包管理工具 (npm)
- JS 性能优化之防抖
文章评论
评论问答