
使用字符串对象的 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']Array.toString()
数组转为字符串可以使用 toString 方法,但是这个方法不能自定义分割符,默认分割符为英文逗号 ,
const lang = ['html', 'css', 'js', 'vue']const string = lang.toString()console.log(string) //html,css,js,vueArray.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