Pilcrow Records

Scripter Javascript Tutorial

javascriptmusiclogicscripterbookexcerpttutorial

45 Add Data to an Array

Adding data to an array depends on the state of the array. One of the most common methods is to use the push() function of an array, which adds a new value to the end of the array.

var scale = [];
scale.push(60); // [60]
scale.push(62); // [60, 62]

In JavaScript, data can be added beyond the bounds of the array and the array will automatically increase in length to accommodate the value.

var scale = []; // an empty array
scale[2] = 60; // [,,60] two empty values and then the added value

The unshift() function adds a value to the beginning of the array:

var scale = [69, 71, 72];
var last = scale.unshift(67); 
// scale = 67, 69, 71, 72