Array Methods
Tags : JavaScript Intro
Array Methods
- pop() : removes the last element of the array and returns it.
- push() : adds an element at the end and returns the arrays length.
- shift() : removes the first element in the array and returns it.
- unshift() : adds an element at the beginning and returns the arrays length
- join() : joins every element of the array as a single string.
- indexOf() : if it finds an element it returns it's index else it returns -1.
Check the Mozilla page for more info
var example = ["hello", "there"];
// call example
example
// returns ["hello", "there"]
example.pop()
// pop() removes the last element of the array and returns it.
// returns "there"
example
// returns ["hello"]
// Let's add "there" back into the array
example.push("there")
// push() adds an element at the end and returns the arrays length.
// should return 2 (length of the array; how many elements in the array)
example
// returns ["hello", "there"]
example.shift()
// Shift removes the first element in the array and returns it.
// returns "hello"
example
// returns ["there"]
// Let's add "hello" back into the array
example.unshift("hello")
// unshift adds an element at the beginning and returns the arrays length.
// returns 2, the length of the array
example
// returns ["hello", "there"]
// join method, joins every element in the array.
example.join()
// each element inside the string will be separated by a comma by default.
// returns "hello,there"
example.join(", ");
// If we add an argument to the join() method we can change how it separates each element.
// every element will be separated by " " (space)
// returns "hello there"
example.join(", ");
// returns "hello, there"
example.indexOf("hello")
// indexOf returns the index if it matches an element.
// otherwise it returns -1
// returns 0, as "hello" is the first element of the array
example.indexOf("bye")
// returns -1, "bye" is not present in the array.
example.indexOf("there")
// returns 1
Try the following:
- Build your own array. You can use strings, numbers, booleans (true or false) and even variables.
- Use pop(), push(), shift() and unshift() on your array.
- Use join() to turn your array into a string.
- Use indexOf() to find an element of an array.