js数组切割方法 splice和slice的区别

一:数组转字符串(3种方法)同样是数组转字符串,toString(),toLocaleString(),join(),join(‘,’)的区别是什么?
JavaScript 允许数组与字符串之间相互转换 。其中 Array 方法对象定义了 3 个方法,可以把数组转换为字符串,如表所示 。
数组方法说明toString()将数组转换成一个字符串toLocaleString()把数组转换成本地约定的字符串join()将数组元素连接起来以构建一个字符串1:join()方法用于把数组中的所有元素放入一个字符串【js数组切割方法 splice和slice的区别】元素是通过指定的分隔符进行分隔的
join()指定的分隔符说明join()可理解为直接变成字符串,默认逗号分隔join(‘ ‘)空连接join(‘,’)或者 join(‘ – ‘)或者 join(‘。’)中间这个逗号是手动添加的,也可以改成别的比如、 。! -等等都可以// join()var a= ["00", "01", "02", "03", "04"]var b=a.join()console.log(b)console.log( typeof b)//打印结果00,01,02,03,04// join('')var a= ["00", "01", "02", "03", "04"]var b=a.join('')console.log(b)console.log( typeof b)//打印结果0001020304// join(',')var a= ["00", "01", "02", "03", "04"]var b=a.join(',')console.log(b)console.log( typeof b)//打印结果00,01,02,03,04或者// join('-')var a= ["00", "01", "02", "03", "04"]var b=a.join('-')console.log(b)console.log( typeof b)//打印结果00-01-02-03-04或者// join('!')var a= ["00", "01", "02", "03", "04"]var b=a.join('!')console.log(b)console.log( typeof b)//打印结果 00!01!02!03!042:toString()方法可把一个逻辑值转换为字符串,并返回结果var a= ["00", "01", "02", "03", "04"]var c = a.toString();//把数组转换为字符串console.log(c)console.log(typeof c);//返回字符串string,说明是字符串类型//打印结果00,01,02,03,04toString()方法不可以指定分隔符,但是我们可以通过replace()方法指定替换
var a= ["00", "01", "02", "03", "04"]var f = a.toString().replace(/,/gi,'-')console.log(f)//打印结果:00-01-02-03-043:toLocaleString()把数组转换成本地约定的字符串
var a= ["00", "01", "02", "03", "04"]var e = a.toLocaleString();console.log(e)console.log(typeof e);//打印结果:00,01,02,03,04demo
<!DOCTYPE html><html><head><meta charset="UTF-8"><script src="http://pic.caodingtushuguan.com/221001/0224593H1-0.jpg"></script><title></title></head><body></body><script type="text/javascript">var a= ["00", "01", "02", "03", "04"]//1:var b=a.join(',')console.log(b)console.log( typeof b)//2:var c = a.toString();//把数组转换为字符串console.log(c)console.log(typeof c);//返回字符串string,说明是字符串类型//3:var d = a.join();//把数组转换为字符串console.log(d)console.log(typeof d);//返回字符串string,说明是字符串类型//4:var e = a.toLocaleString();//把数组转换为字符串console.log(e)console.log(typeof e);//返回字符串string,说明是字符串类型</script></html>

js数组切割方法 splice和slice的区别

文章插图
js数组切割方法 splice和slice的区别

文章插图
二:字符串转数组(2种方法)字符串方法说明split() 方法将字符串转换成一个数组扩展运算符(…)es6里面的扩展运算符字符串转数组
1:split() 方法用于把一个字符串分割成字符串数组同样是用于把一个字符串分割成字符串数组,split(‘,’),split(),split(‘ ‘)的区别是什么?
split()方法说明split(‘,’)split()可理解为直接变成字符串,默认逗号分隔split(‘ ‘) 空字符串每个字符之间都会被分割var arr = 'aa,bb,cc,dd'var newStr = arr.split(',')console.log(newStr) // 打印结果:["aa", "bb", "cc", "dd"]var arr = 'aa,bb,cc,dd'var newStr = arr.split()console.log(newStr)// 打印结果: ["aa,bb,cc,dd"]如果把空字符串 (“”) 用作 separator,那么 stringObject 中的每个字符之间都会被分割
var arr = 'aa,bb,cc,dd'var newStr = arr.split('')console.log(newStr) //打印结果: ["a", "a", ",", "b", "b", ",", "c", "c", ",", "d", "d"]2:es6里面的扩展运算符var arr = 'aa,bb,cc,dd'var newStr = [...arr]console.log(newStr) //打印结果 ["a", "a", ",", "b", "b", ",", "c", "c", ",", "d", "d"]以上就是js数组与字符串相互转换的几种方法啦~∠( °ω°)/ ~

    推荐阅读