The concat() method returns the array
resulting from appending its arguments to
the array on which it was invoked.
Given the script:
var myArray = ["red", "green", "blue"]; alert(myArray.concat("cyan", "yellow"));
Be careful, though; concat() does not modify the
array in place. Notice the output of this script,
var myArray = ["red", "green", "blue"];
myArray.concat("cyan", "yellow");
alert(myArray);
Unlike with the push() and shift() methods discussed earlier, you will need to save the
returned value; for example:
var myArray = ["red", "green", "blue"]; myArray = myArray.concat("cyan", "yellow");
If any argument to concat() is itself an array,
it is flattened into array elements. This flattening is not recursive, so an
array argument that contains an array element has only its outer array
flattened. An example illustrates this behavior more clearly:
var myArray = ["red", "green", "blue"]; myArray.concat("pink", ["purple", "black"]); // Returns ["red", "green", "blue", "pink", "purple", "black"] myArray.concat("white", ["gray", ["orange", "magenta"]]); // Returns ["red", "green", "blue", "white", "gray", ["orange", "magenta"]] alert(myArray[myArray.length-1]); // shows orange, magenta
Note |
You may notice that arrays are recursively
flattened if you output the entire array with an alert. However, access the length property or the
individual elements and it will become apparent that you have nested arrays.
|