JS 字符串和数组相互转换
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
本站发布的内容若侵犯到您的权益,请邮件联系站长删除,我们将及时处理!
从您进入本站开始,已表示您已同意接受本站【免责声明】中的一切条款!
本站大部分下载资源收集于网络,不保证其完整性以及安全性,请下载后自行研究。
本站资源仅供学习和交流使用,版权归原作者所有,请勿商业运营、违法使用和传播!请在下载后24小时之内自觉删除。
若作商业用途,请购买正版,由于未及时购买和付费发生的侵权行为,使用者自行承担,概与本站无关。