其他分享
首页 > 其他分享> > 数组的连接和截取(contact和slice和splice)

数组的连接和截取(contact和slice和splice)

作者:互联网

 1 <script>
 2 
 3     var arr1 = ["a","b","c"];
 4     var arr2 = [1,2,3];
 5     
 6      //concat把数组链接在一起
 7     var arr3 = arr1.concat(arr2);
 8     var arr4 = arr2.concat(arr1);
 9     //    console.log(arr1);//a、b、c
10 //    console.log(arr2);//1,2,3
11 //    console.log(arr3);//"a","b","c",1,2,3
12 //    console.log(arr4);//1,2,3,"a","b","c"
13     //slice数组的截取,索引值包左不包右
14     //    var arr = arr3.slice(2);//["c",1,2,3],
15 
16 //splice
17 定义和用法
18 splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目。
19 
20 注释:该方法会改变原始数组。
21 
22 语法
23 arrayObject.splice(index,howmany,item1,.....,itemX)
24 参数                  描述
25 index                必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置。
26 howmany               必需。要删除的项目数量。如果设置为 0,则不会删除项目。
27 item1, ..., itemX        可选。向数组添加的新项目。
28 
29 //例子1:在本例中,我们将创建一个新数组,并向其添加一个元素:
30 var arr = new Array(6)
31 arr[0] = "George"
32 arr[1] = "John"
33 arr[2] = "Thomas"
34 arr[3] = "James"
35 arr[4] = "Adrew"
36 arr[5] = "Martin"
37 
38 document.write(arr + "<br />")
39 arr.splice(2,0,"William")
40 document.write(arr + "<br />")
41 输出:
42 
43 George,John,Thomas,James,Adrew,Martin
44 George,John,William,Thomas,James,Adrew,Martin
45 
46 //例子2:在本例中我们将删除位于 index 2 的元素,并添加一个新元素来替代被删除的元素:
47 var arr = new Array(6)
48 arr[0] = "George"
49 arr[1] = "John"
50 arr[2] = "Thomas"
51 arr[3] = "James"
52 arr[4] = "Adrew"
53 arr[5] = "Martin"
54 
55 document.write(arr + "<br />")
56 arr.splice(2,1,"William")
57 document.write(arr)
58 输出:
59 
60 George,John,Thomas,James,Adrew,Martin
61 George,John,William,James,Adrew,Martin
62 
63 //例子3:在本例中我们将删除从 index 2 ("Thomas") 开始的三个元素,并添加一个新元素 ("William") 来替代被删除的元素:
64 <script type="text/javascript">
65 
66 var arr = new Array(6)
67 arr[0] = "George"
68 arr[1] = "John"
69 arr[2] = "Thomas"
70 arr[3] = "James"
71 arr[4] = "Adrew"
72 arr[5] = "Martin"
73 
74 document.write(arr + "<br />")
75 arr.splice(2,3,"William")
76 document.write(arr)
77 
78 输出:
79 
80 George,John,Thomas,James,Adrew,Martin
81 George,John,William,Martin
82 
83 </script>

 

标签:arr,slice,James,Adrew,contact,splice,Martin,John,George
来源: https://www.cnblogs.com/my12-28/p/11740495.html