Array Object: Built-in Methods

by Lucille Kenney

HTML

<div>
    <p>The built-in Array object provides some helpful methods for manipulating arrays.</p>
    <p>The way to find out some of what you can do with an array is to look in a reference. As we've seen, there are many references and each can be useful in its own way.  We'll be looking at <a href="http://www.w3schools.com/jsref/jsref_obj_array.asp" target="_blank">W3Schools JS Array Reference</a> for its simplicity, or the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" target="_blank">MDN Array Reference</a> for its completeness. </p>
    <p></p>
    <p>Output will appear below:</p>
</div>
<div id="output"></div>

CSS

#output{
    width:80%;
    border: 1px solid black;
    padding: 1em;
}

JavaScript

var myFavoritePets = ["dog","cat","kangaroo","whale"];

// We'll use Array.join() to create a string 
//  containing the array elements (delimited by
//  HMTL, in this case).
var bigString = myFavoritePets.join("<br>");
console.log(bigString);
logMessage(bigString + " is a " + typeof bigString);

logMessage("<hr>");

// Now we use String.split() to go the other way
//  from a string to an array
var newPetsArray = bigString.split("<br>");
console.log(newPetsArray);
logMessage(newPetsArray + " is a " + typeof newPetsArray) ;
logMessage("Specifically, newPetsArray is an " + newPetsArray.constructor.name);



// Utility function for logging convenience
// Logs msg to the element with given id
// If id is undefined, logs to #output
function logMessage(msg, id){
    if (!id){
        id="output";
    }
    document.getElementById(id).innerHTML += msg + "<br>";
}