同样是数组转字符串,toString(),toLocaleString(),join(),join(',')的区别是什么?
JavaScript允许数组与字符串之间相互转换。其中Array方法对象定义了3个方法,可以把数组转换为字符串,如表所示。
数组方法 | 说明 |
toString() | 将数组转换成一个字符串 |
toLocaleString() | 把数组转换成本地约定的字符串 |
join() | 将数组元素连接起来以构建一个字符串 |
1:join()方法用于把数组中的所有元素放入一个字符串
元素是通过指定的分隔符进行分隔的
join()指定的分隔符 | 说明 |
join() | 可理解为直接变成字符串,默认逗号分隔 |
join('') | 空连接 |
join(',')或者join('-')或者join('。') | 中间这个逗号是手动添加的,也可以改成别的比如、。!-等等都可以 |
//join()vara=["00","01","02","03","04"]varb=a.join()console.log(b)console.log(typeofb)//打印结果00,01,02,03,04
//join('')vara=["00","01","02","03","04"]varb=a.join('')console.log(b)console.log(typeofb)//打印结果0001020304
//join(',')vara=["00","01","02","03","04"]varb=a.join(',')console.log(b)console.log(typeofb)//打印结果00,01,02,03,04或者//join('-')vara=["00","01","02","03","04"]varb=a.join('-')console.log(b)console.log(typeofb)//打印结果00-01-02-03-04或者//join('!')vara=["00","01","02","03","04"]varb=a.join('!')console.log(b)console.log(typeofb)//打印结果00!01!02!03!04
2:toString()方法可把一个逻辑值转换为字符串,并返回结果
vara=["00","01","02","03","04"]varc=a.toString();//把数组转换为字符串console.log(c)console.log(typeofc);//返回字符串string,说明是字符串类型//打印结果00,01,02,03,04
toString()方法不可以指定分隔符,但是我们可以通过replace()方法指定替换
vara=["00","01","02","03","04"]varf=a.toString().replace(/,/gi,'-')console.log(f)//打印结果:00-01-02-03-04
3:toLocaleString()
把数组转换成本地约定的字符串
vara=["00","01","02","03","04"]vare=a.toLocaleString();console.log(e)console.log(typeofe);//打印结果:00,01,02,03,04
demo
<!DOCTYPEhtml><html><head><metacharset="UTF-8"><scriptsrc="https://img.pc-daily.com/uploads/allimg/220113/140AGM5-0.jpg"></script><title></title></head><body></body><scripttype="text/javascript">vara=["00","01","02","03","04"]//1:varb=a.join(',')console.log(b)console.log(typeofb)//2:varc=a.toString();//把数组转换为字符串console.log(c)console.log(typeofc);//返回字符串string,说明是字符串类型//3:vard=a.join();//把数组转换为字符串console.log(d)console.log(typeofd);//返回字符串string,说明是字符串类型//4:vare=a.toLocaleString();//把数组转换为字符串console.log(e)console.log(typeofe);//返回字符串string,说明是字符串类型</script></html>
二:字符串转数组(2种方法)
字符串方法 | 说明 |
split()方法 | 将字符串转换成一个数组 |
扩展运算符(...) | es6里面的扩展运算符 |
字符串转数组
1:split()方法用于把一个字符串分割成字符串数组
同样是用于把一个字符串分割成字符串数组,split(','),split(),split('')的区别是什么?
split()方法 | 说明 |
split(',') | |
split() | 可理解为直接变成字符串,默认逗号分隔 |
split('')空字符串 | 每个字符之间都会被分割 |
vararr='aa,bb,cc,dd'varnewStr=arr.split(',')console.log(newStr)//打印结果:["aa","bb","cc","dd"]
vararr='aa,bb,cc,dd'varnewStr=arr.split()console.log(newStr)//打印结果:["aa,bb,cc,dd"]
如果把空字符串("")用作separator,那么stringObject中的每个字符之间都会被分割
vararr='aa,bb,cc,dd'varnewStr=arr.split('')console.log(newStr)//打印结果:["a","a",",","b","b",",","c","c",",","d","d"]
2:es6里面的扩展运算符
//join('')vara=["00","01","02","03","04"]varb=a.join('')console.log(b)console.log(typeofb)//打印结果00010203040
以上就是js数组与字符串相互转换的几种方法啦~∠(°ω°)/~