前端设计

concat函数在js中的使用

2018-11-27

concat() 方法用于连接两个或多个数组。

arrayObject.concat(arrayX,arrayX,......,arrayX)

该方法不会改变现有的数组,而仅仅会返回被连接数组的一个副本

  mya[0] = "1";

  mya[1] = "2";

  mya[2] = "3";

  document.write(mya.concat(4,5)+"");

  document.write(mya); 

运行结果:

1,2,3,4,5

1,2,3

--------------------------

我们将把 concat() 中的参数连接到数组 a 中:

<script>

var a = [1,2,3];

document.write(a.concat(4,5));

</script>

输出:1,2,3,4,5

---------------------------

我们创建了两个数组,然后使用 concat() 把它们连接起来:

<script>

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

-------------------------------------

创建三个数组,然后使用 concat() 把它们连接起来:

<script>

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