Sunday, 1 September 2013

Js Arrays: Functions

Okay so let's run through some javascript arrays.
I'm going to try and cover some of the more useful functions in array manipulation.
too start out we're going to use this five element array.

Our array

var v = ["a","b","c", "d","e"];
console.log(v.length); // 5

Index 0 Index 1 Index 2 Index 3 Index 4
a b c d e


v[9] = "j";
console.log(v[9]); // j
console.log(v[v.length - 1]); // j
console.log(v.length); // 10

Index 0 Index 1 Index 2 Index 3 Index 4 5 6 7 8 Index 9
a b c d e undefined j


PUSH & POP

~ works with the END of the array

PUSH

//push() appends one or more items to the end of the array
v.push("f");
console.log(v.length); // 6
console.log(v[5]); // f

And for your info push could also be achieved by
v[v.length] = "f"

Index 0 Index 1 Index 2 Index 3 Index 4 Index 5
a b c d e f

To add multiple elements
v.push("g","h","i");

POP

console.log(v.length); // 6
console.log(v[v.length]); // f

v.pop(); // f

console.log(v.length); // 5
console.log(v[v.length]); // e

Index 0 Index 1 Index 2 Index 3 Index 4
a b c d e


//pop() on an empty array returns undefined

UNSHIFT & SHIFT

~ works with the START of the array


UNSHIFT

v.unshift("f"); //prepends one or more items to the start of the array
//v.unshift("f","o","o");
console.log(v.length); // 6
console.log(v[0]); // f

Index 0 Index 1 Index 2 Index 3 Index 4 Index 5
f a b c d e


SHIFT

console.log(v.length); // 6
console.log(v[0]); // f

//shift() returns the first item from the array and shrinks it
v.shift(); // f

console.log(v.length); // 5
console.log(v[0]); // a

Index 0 Index 1 Index 2 Index 3 Index 4
a b c d e


Merging arrays

Concat

is used to join two or more arrays.
var tail = ["x","y","z"];
var num = ["1","2","3"];

//concat() returns an array of the joined arrays
var v2 = v.concat(tail, num); //["a","b","c", "d","e","x","y","z","1","2","3"]

console.log(v.length); // 5
console.log(v2.length); // 11

0 1 2 3 4 5 6 7 8 9 10
a b c d e x y z 1 2 3

Well I think that's me done for a while.
Till next time kids.

No comments:

Post a comment