This document discusses several built-in array methods in JavaScript including push/pop to add/remove from the end of an array, shift/unshift to add/remove from the beginning, indexOf to find an element's index, slice to copy part of an array, and splice to remove elements from an array. Examples are provided for each method demonstrating how to use them and the return values. An exercise at the end demonstrates using slice() to copy part of an array and an entire array.
This document discusses several built-in array methods in JavaScript including push/pop to add/remove from the end of an array, shift/unshift to add/remove from the beginning, indexOf to find an element's index, slice to copy part of an array, and splice to remove elements from an array. Examples are provided for each method demonstrating how to use them and the return values. An exercise at the end demonstrates using slice() to copy part of an array and an entire array.
Objectives Arrays come with a few built-in methods that make our life easier. We're going to cover: push/pop shift/unshift indexOf slice Push and Pop Use push to add to the end of an array:
var col = colors.shift(); //orange IndexOf Use indexOf() to find the index of an item in an array var friends = ["Charlie", "Liz", "David", "Mattias", "Liz"];
//returns the first index at which a given element can be found
friends.indexOf("David"); //2 friends.indexOf("Liz"); //1, not 4
//returns -1 if the element is not present.
friends.indexOf("Hagrid"); //-1 Slice Use slice() to copy parts of an array var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']; //use slice to copy the 2nd and 3d fruits //specify index where the new array starts(1) and ends(3) var citrus = fruits.slice(1, 3);
//you can also use slice() to copy an entire array
var nums = [1,2,3]; var otherNums = nums.slice(); //both arrays are [1,2,3] Splice Use splice to remove var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']; //use splice to remove 'Orange' from the array //specify index of the element to be removed and //how many elements should be removed from that index fruits.splice(1, 1); // returns: ["Orange"] console.log(fruits); // prints: ["Banana", "Lemon", "Apple", "Mango"] Array Methods Exercise 1 var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']; //use slice to copy the 2nd and 3d fruits //specify index where the new array starts(1) and ends(3) var citrus = fruits.slice(1, 3);