JavaScript数组操作函数汇总(2)

<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.join() + "<br />") arr.splice(2,0,"William") document.write(arr.join() + "<br />") </script>

输出:
George,John,Thomas,James,Adrew,Martin
George,John,William,Thomas,James,Adrew,Martin
例子 2
在本例中我们将删除位于 index 2 的元素,并添加一个新元素来替代被删除的元素:

<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.join() + "<br />") arr.splice(2,1,"William") document.write(arr.join()) </script>

输出:
George,John,Thomas,James,Adrew,Martin
George,John,William,James,Adrew,Martin
例子 3
在本例中我们将删除从 index 2 ("Thomas") 开始的三个元素,并添加一个新元素 ("William") 来替代被删除的元素:

<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.join() + "<br />") arr.splice(2,3,"William") document.write(arr.join()) </script>

输出:
George,John,Thomas,James,Adrew,Martin
George,John,William,Martin

(6)contact()
该方法用于连接两个或多个数组。它不会改变现有的数组,而仅仅会返回被连接数组的一个副本。
语法
arrayObject.concat(arrayX,arrayX,......,arrayX)
示例:
例子 1
在本例中,我们将把 concat() 中的参数连接到数组 a 中:

<script type="text/javascript"> var a = [1,2,3]; document.write(a.concat(4,5)); </script>

输出:
1,2,3,4,5
例子 2
在本例中,我们创建了两个数组,然后使用 concat() 把它们连接起来:

<script type="text/javascript"> var arr = new Array(3) arr[0] = "George" arr[1] = "John" arr[2] = "Thomas" var arr2 = new Array(3) arr2[0] = "James" arr2[1] = "Adrew" arr2[2] = "Martin" document.write(arr.concat(arr2)) </script>

输出:
George,John,Thomas,James,Adrew,Martin
例子 3
在本例中,我们创建了三个数组,然后使用 concat() 把它们连接起来:

<script type="text/javascript"> var arr = new Array(3) arr[0] = "George" arr[1] = "John" arr[2] = "Thomas" var arr2 = new Array(3) arr2[0] = "James" arr2[1] = "Adrew" arr2[2] = "Martin" var arr3 = new Array(2) arr3[0] = "William" arr3[1] = "Franklin" document.write(arr.concat(arr2,arr3)) </script>

输出:
George,John,Thomas,James,Adrew,Martin,William,Franklin

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzxdgp.html