详解JS中的join,splice,slice,split的区别
转载:https://blog.csdn.net/tt_twilight/article/details/101547604
1.join:
join()方法用于把数组中的所有元素通过指定的分隔符分隔之后,再放入一个字符串。
栗子:
<script type="text/javascript"> var arr = new Array(3) arr[0] = "George" arr[1] = "John" arr[2] = "Thomas" document.write( arr.join() ) </script>
运行结果:
George,John,Thomas
2.split
split()方法用于把一个字符串以特定字符分割成字符串数组并返回。
第一个参数是指定的分割字符;字符存在于字符串中,且分割后不存在于字符串数组中。
第二个参数是指定分割之后字符串数组的长度。(可选)
栗子:
<script type="text/javascript"> var str="How are you doing today?" document.write(str.split(" ") + "<br />") document.write(str.split("") + "<br />") document.write(str.split(" ",3)) </script>
How,are,you,doing,today?
H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?
How,are,you
3.slice
slice()方法从已有的数组中返回特定的元素。
第一个参数是开始索引(从0开始)
第二个参数是结束索引的下一个(可选,默认到最后一个)
栗子:
<script type="text/javascript"> var arr = new Array(6) arr[0] = "George" arr[1] = "John" arr[2] = "Thomas" arr[3] = "James" arr[4] = "Adrew" arr[5] = "Martin" document.write(arr + "<br />") document.write( arr.slice(2,4) + "<br />") document.write(arr) </script>
运行结果:
George,John,Thomas,James,Adrew,Martin
Thomas,James
George,John,Thomas,James,Adrew,Martin
4.splice
splice()方法从数组中添加/删除元素,并返回被删除的元素。
第一个参数代表开始删除的位置,第二个参数代表删除个数,第三个参数为添加的元素(元素添加在开始删除的位置之前)。
栗子:
<script type="text/javascript"> var arr = new Array(6) arr[0] = "George" arr[1] = "John" arr[2] = "Thomas" arr[3] = "James" arr[4] = "Adrew" arr[5] = "Martin" document.write(arr + "<br />") arr.splice(2,0,"William") document.write(arr + "<br />") </script>
运行结果:
George,John,Thomas,James,Adrew,Martin
George,John,William,Thomas,James,Adrew,Martin
<script type="text/javascript"> var arr = new Array(6) arr[0] = "George" arr[1] = "John" arr[2] = "Thomas" arr[3] = "James" arr[4] = "Adrew" arr[5] = "Martin" document.write(arr + "<br />") arr.splice(2,1,"William") document.write(arr) </script>
运行结果:
George,John,Thomas,James,Adrew,Martin
George,John,William,James,Adrew,Martin
-
<script type="text/javascript"> var arr = new Array(6) arr[0] = "George" arr[1] = "John" arr[2] = "Thomas" arr[3] = "James" arr[4] = "Adrew" arr[5] = "Martin" document.write(arr + "<br />") arr.splice(2,3,"William") document.write(arr) </script>
运行结果:
George,John,Thomas,James,Adrew,Martin
George,John,William,Martin