We left off a while back discussing the various built-in Date Objects that JavaScript has to offer. Prior to that we talked about String Objects and JavaScript Events. Here and now, we are going to go over the Array Objects, which we can use to manipulate arrays. We will start off by viewing a table of them and the definitions of each. After that we will begin with the concat() method and try our best to work our way through the remaining thirteen.
There's plenty to discuss, and little space to do it in, so let's get started:
Method
What It Does
concat()
Used to join two (or more) arrays together and return the result.
join()
Used to place every element of an array into a delimiter separated string. You specify the delimiter.
pop()
Used to remove and return the right most (the last) element in an array.
push()
Used to add one (or more) elements to the right most (end) of an array and then return the modified array length.
reverse()
Used to reverse the order of the elements in a given array.
shift()
Used to remove the left most (first) element in an array and return it.
slice()
Used to return given elements from an array.
splice()
Used to remove or add elements to/from an array.
sort()
Used to sort the elements within an array.
toSource()
Represents an object's source code.
toString()
Used to convert an array to a string. Returns the result.
unshift()
Used to add one (or more) elements to the left side (beginning) of an array and return the modified array length.
valueOf()
Used to retrieve the primitive value of an array object.
Concat(): Sticking Together
With concat(), we can join two or more arrays together. It's a pretty simple method. Here it is in code:
<html>
<body>
<script type="text/javascript">
var bboys = new Array(5);
bboys[0] = "Greg";
bboys[1] = "Bobby";
bboys[2] = "Peter";
bboys[3] = "Mike";
bboys[4] = "Alice";
var bgirls = new Array(4);
bgirls[0] = "Marcia";
bgirls[1] = "Carol";
bgirls[2] = "Jan";
bgirls[3] = "Cindy";
document.write("Behold the Brady Bunch: ");
document.write(bboys.concat(bgirls));
</script>
</body>
</html>
Here, we create two arrays, bboys and bgirls, and assign them the values of the Brady Bunch males and females, respectively. We then combine the two together using the concat() method, giving us this result: