Monday, August 10, 2015

JavaScript Arrays

A JavaScript array is an ordered collection of values: a value is called array's element, a value's numeric position is called the element's index.
JavaScript arrays indexes are 32-bits unsigned integer values: the index of the first element is 0, and the highest possible index is (232−2) ≡ 4,294,967,294.
Array values may be of any type and different types can be present in the same array.
JavaScript arrays are dynamic: they grow or shrink according to what is necessary.
A JavaScript array may be dense or sparse:
  • a dense array is an array whose element indexes are contiguous
  • a sparse array is an array whose element indexes are NOT contiguous: it have gaps/holes.
Every JavaScript arrays has a length property:
  • if the array is dense, the length property equals the number of elements and its value is one more than the highest index in the array.
  • if the array is sparse, the length property is greater than the number of elements.

1 Creating Arrays

Two ways to create a JavaScript array:
  • with array literals notation
  • with the Array() constructor
1.1 Creating arrays with literal notation
You can create an array with an array literal, which is simply a comma separated list of array elements within square brackets.
For example:
var empty = []; // An array with no elements
console.log(empty); // []
    
var powerOfTwo = [1, 2, 4, 8, 16, 32, 64, 128, 256]; // An array with 9 numeric elements
console.log(powerOfTwo); // [1, 2, 4, 8, 16, 32, 64, 128, 256]

var miscellaneous = [ 2.73, true, "string", ]; // 3 elements of various types + trailing comma
console.log(miscellaneous ); // [2.73, true, "string"]

Array literals can contain object literals or other array literals:

var actors = [ 
    [ 1, {firstName: 'Uma', lastName: 'Thurman'} ], 
    [ 2, {firstName: 'Michael', lastName: 'Douglas'} ] 
];
console.log(actors); // [ Array[2], Array[2] ]

If you omit a value from an array literal, you have created a sparse array:

var count = ["one",,"three"]; // A sparse array with length 3.
console.log(count); // ["one", 2:, "three"]
    
var sparse = [,,]; // A sparse array with length 2.    
console.log(sparse); // [ <2 empty="" slots=""> ]
1.2 Creating arrays with Array() constructor
You can create an array invoking the Array() constructor. You can invoke the Array() constructor in three different ways:
// with no arguments:
var empty = new Array(); // empty array, like []
console.log(empty); // []
 
// with a single numeric arguments that become the array length.
// This allocates an array with no elements and no indexes
var arr2 = new Array(10); // a sparse array of length 10
console.log(arr2); // [] 
    
// with two or more arguments that become array elements
var arr3 = new Array(5, 10, "third elem", "fourth elem");
console.log(arr3); // [5, 10, "third elem", "fourth elem"]

2 Reading and Writing Array Elements

You read and write array elements using the square brackets operator [ ]
array[expression]
where:
  • array is a reference to the array object
  • expression evaluate to a non-negative integer value
Example: writing array elements
var array = [];
var i = 0;
array[i] = "hello"; // write element with index 0
array[i+1] = "world"; // write element with index 1
console.log(array); // ["hello", "world"]
Example: reading array elements
var array2 = ["good bye","blue sky"];    
// reading elements with indexes 0 and 1
var string = array2[0] + ", " + array2[1];
console.log(string); // "good bye, blue sky"

Arrays are a specialized kind of object.

You can access object properties using the square brackets like you access array elements. Since array are objects, in accessing an array's elements, array indexes are converted to string and treated as property names. In fact, when dealing with objects every property name is implicitly converted to string.
var object = {
  1: "a property"
};
object[2] = "another property";
console.log(object); // Object {1: "a property", 2: "another property"}

What is arrays' special feature?

When you index an array using property names that are non-negative integers, less than 232, the array automatically updates the value of the length property.
var array = [];
array[0] = "hello"; // write element with index 0
array[1] = "world"; // write element with index 1
console.log(array.length) // 2

3 Array Length

JavaScript arrays have a length property, and this characteristic makes arrays different from ordinary objects.
If the array is dense, the length property equals the number of elements and its value is one more than the highest index in the array.
var array = []; // no elements
array.length; // 0

var array2 = [1, 2, 3, 4, 5]; // five elements
array2.length; // 5: the greatest index is 4

4 Adding and Deleting Array Elements

How to add elements
  • by assigning a value to a new index
  • the push() method adds elements to the end of an array
  • the unshift() method inserts a value at the beginning of an array, this shifts the existing values to elements with greater indexes.
Example: adding a value to a new index
a = [] // Start with an empty array.
a[0] = "zero"; // And add elements to it.
a[1] = "one";

Example: adding values with push() and unshift() methods

var arr = [0]; // an array with an element.

// add two values at the end
arr.push(1);
arr.push(2);
console.log(arr); // [0, 1, 2]

// add two more values at the beginning
arr.unshift(-1); 
arr.unshift(-2);    
console.log(arr); // [-2, -1, 0, 1, 2]
How to delete elements
  • the pop() method removes the last element
  • the shift() method removes the first element
  • the delete operator removes an element, but the array becomes sparse
  • setting the length property to an integer n smaller than its current value remove all the elements with index greater or equal than n

Example: deleting values with pop() and shift() methods

var array = [-2, -1, 0, 1, 2];
array.pop(); // remove the last
console.log(array); // [-2, -1, 0, 1]
array.shift(); // remove the first
console.log(array); // [-1, 0, 1]

6 Iterating Arrays

You can iterate arrays:

  • with for loop
  • with forEach() method
  • with Object.keys() for loop
  • with for/in loop

Example - iterating arrays with a for loop

var array = ["zero", "one", "two","three", "four"];
var out = "";
for(var i=0; i<array.length; i++) {
    var value = array[i];
    out += value+" ";
}
console.log(out); // "zero one two three four "

If you want to iterate a sparse array you have to check for nonexistent elements with: if (!(i in array)) continue;

Example - iterating arrays with a forEach method

the forEach() method passes each array element to a function that you define. The forEach() method skips sparse array nonexistent elements

var array = ["zero", "one", "two", "three", "four"];
var out = "";
array.forEach(function(value){
                out += value+" ";     
              })
console.log(out); // "zero one two three four "

Example - iterating arrays with a for/in loop

var array = ["zero", "one", "two", "three", "four"];
var out = "";
for(i in array){
    var value = array[i];
    out += value+" ";     
}
console.log(out); // "zero one two three four "

If you want to skip inherited properties you have to test with: if (!array.hasOwnProperty(i)) continue;

Example - iterating arrays with a Object.keys() for loop

var array = ["zero", "one", "two", "three", "four"];
var out = "";
var keys = Object.keys(array);
var values = []; 
for(var i = 0; i < keys.length; i++) {
    var key = keys[i];
    out += array[key]+" ";
}
console.log(out); // "zero one two three four "



No comments :

Post a Comment