JavaScript Tutorial/Array/Concat

Материал из Web эксперт
Перейти к: навигация, поиск

Actual success in copying an array using concat()

<html>
<head>
<title>Actual success in copying an array using concat()</title>
<script type="text/javascript" language="javascript">
<!-- //
function CopyArray(){
var myArray = new Array(1,2,3);
var emptyArray = new Array();
var myCopy  = myArray.concat(emptyArray);
    myArray[0] = 10;
    myArray[1] = 20;
    myArray[2] = 30;
var ma = myArray.join(", ");
var mc = myCopy.join(", ");
alert(ma);
alert(mc);
}
// -->
</script>
</head>
<body onload="CopyArray()">
</body>
</html>


Array.concat()

Syntax array.concat(arg1,...argN)

The concat() method adds the elements listed in the parameter list to the end of the existing array and returns the result.

arg1,...argN contains one or more elements to be concatenated to the end of the array.

The original is not changed by this method.



<html>
    <script language="JavaScript">
    <!--
    function displayElements(theArray)
    {
      for(i=0; i<theArray.length; i++)
      {
        document.write(" - ",theArray[i][1]," ");
        document.write(theArray[i][0],"<br>");
      }
    }
    shelf1 = new Array(["A",10],["B",25]);
    document.write("Shelf 1 contains:<br>");
    displayElements(shelf1);
    
    shelf2 = new Array(["C",50],["D",3],["E",8]);
    document.write("Shelf 2 contains:<br>");
    displayElements(shelf2);
    
    inventory = shelf1.concat(shelf2);
    document.write("<br>The total inventory contains:<br>");
    displayElements(inventory);
    --></script>
    </html>


Using concat() method to combine two arrays

<html>
<head>
<title>Using concat() method to combine two arrays</title>
<script type="text/javascript" language="javascript">
<!-- //
function ConcatArrays(){
var firstArray  = new Array(1,2,3);
var secondArray = new Array(4,5,6);
var combinedArray = firstArray.concat(secondArray);
var fa = firstArray.join(", ");
var sa = secondArray.join(", ");
var ca = combinedArray.join(", ");
document.write("<P>The first array contains: <b>" + fa + " </b></p>");
document.write("The second array contains: <b>" + sa + " </b></p>");
document.write("The combined array contains: <b>" + ca + " </b></p>");
document.write("The combined array length is: <b>" + combinedArray.length + "
</b></p>");
}
// -->
</script>
</head>
<body onload="ConcatArrays()">
</body>
</html>