UX Design and Development course

Working with array properties and methods

Properties: constructor, length and prototype

var cars = ["Toyta", "Ford", "Chevy", "Dodge", "Hummer"];
var motorcycles = ["Harley-Davidson", "Indian", "BMW", "Buell", "Honda"]

console.log(cars.length); // using the .length property

var carsLength = cars.length;
console.log(carsLength);
console.log(cars[carsLength - 1]);

To concatenate the two arrays, using the first object, use the method of .concat and pass in the second object into the parens.

var transportation = cars.concat(motorcycles);

console.log(transportation.length);
console.log(transportation[5]);

See all properties and methods or an array https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Methods

The join method - converts an array to a string

var officeFurniture = ['chair', 'desk', 'shelf', 'lamp']

var allOfficeFurniture = officeFurniture.join('; ');

console.log(allOfficeFurniture);

Fun with array methods

var officeFurnitureLength = officeFurniture.length; // get the array length
console.log(officeFurniture.length); // print value to the view
var officeFurnitureLastElement = officeFurniture.length - 1; // get length - 1
console.log(officeFurniture[officeFurnitureLastElement]); // print last element in the array to the view

officeFurniture.pop(); // removes the last element in the array
console.log(officeFurniture.length);
var officeFurnitureLastElement = officeFurniture.length - 1;
console.log(officeFurniture[officeFurnitureLastElement]);

officeFurniture.push("whiteboard"); // adds new element to the end of the array
console.log(officeFurniture.length);
var officeFurnitureLastElement = officeFurniture.length - 1;
console.log(officeFurniture[officeFurnitureLastElement]);

officeFurniture.reverse(); // reverses the order of the array
console.log(officeFurniture);

officeFurniture.sort(); // alphabetical sorting of the array
console.log(officeFurniture);

Let's add array elements via an event loop

var shoppingList = [];

for (i = 0; i < 3; ++i) {
  shoppingList[i] = prompt('Please enter your list', '');
}

console.log(shoppingList);

Print array elements

var fruit = ['apple', 'orange', 'pineapple', 'cherry', 'kiwi']

fruit.sort();

var fruitLength = fruit.length;

for (i = 0; i < fruitLength; ++i) {
  console.log(fruit[i]);
}

Play with code

JS Bin