Fruited introduction to Array

in Javascript

Alex Girard

Types

Number // 0, 1, .5

String // 'some text', "surrounded by quotes"

Boolean // true, false

Object

Function

Array

Date

RegExp

/* List or collection of values grouped together */

undefined

Syntax


    var fruits           = ['apple', 'orange', 'grappes', 'peach', 'apricot'];

    var examResults      = new Array(15, 12, 7, 16);

    var allocateForLater = new Array(10);

    var empty            = [];

    var mix              = ['Alex', 29, true, ['blue', 180, 76] ];

Accessing elements


    var fruits           = ['apple', 'orange', 'grappes', 'peach', 'apricot'];

    
    fruits[0] == 'apple' // true

    fruits[2] == 'grappes' // true

    fruits[5] == 'apricot' // false

    
    fruits.length // 5

    fruits.indexOf('apple') // 0

    fruits.indexOf('peach') // 3

    fruits.lastIndexOf('apple') // 0

    
 // Get last element of the array

    fruits[fruits.length-1] === 'apricot' // true

Loop through


    var fruits           = ['apple', 'orange', 'grappes', 'peach', 'apricot'];

    
    for(var i=0, l=fruits.length; i<l; ++i){
    
        console.log( fruits[i] ); //print the value at index i
   
    }

Uber useful


    var fruits           = ['apple', 'orange', 'grappes', 'peach', 'apricot'];

    fruits.length === 5 // true
    
    fruits.push('cherry', 'beans');

    fruits.length === 7 // true

    // Oups

    fruits.pop()

    fruits // ['apple', 'orange', 'grappes', 'peach', 'apricot', 'cherry']

Advanced juggling


    var fruits           = ['apple', 'orange', 'grappes', 'peach', 'apricot'];


    fruits.shift() // 'apple'

    fruits // ['orange', 'grappes', 'peach', 'apricot']

    // Explanation: pop the first element of the array


    fruits.splice(1, 1) // ['grappes']

    fruits // ['orange', 'peach', 'apricot']

    // Explanation: remove element(s) given a starting index, and a number of elements


    // end of course...

    fruits.slice(1, 3) // ['peach', 'apricot']

    // Explanation: take begin and end indexes, but exclude the last one of end.
    // Note that it doesn't mutate the array.

Ressources