Sunday, December 8, 2013

Javascript - Array functions



var fruits = [ "apple" , "orange" , "lemon" , "berry"];
var fruits = new Array( "apple" , "orange" , "lemon" , "berry");
Both array instantiations are the same and correct, in which new Array(...) is a more formal way to do that.
Since Javascript is lose type language, it does not care the data type inside the array. Or even you could have a mixed data type with integer and string inside an array.



In Javascript, Array type provides pop(), push(), shift() and unshift() operations for adding or removing elements from an array.
In a Abstract Data Type(ADT) perspective, the pop() and push() operations can be utilised in Stack ADT in a first-in-last-out data structure.
The pop() and unshift() operations can be utilised in Queue ADT as Enqueue and Dequeue respectively.

Similar to my last blog Javascript - String functions, Array class does have some functions which are not implemented in IE 8 or belows.
Array.indexOf() and Array.lastIndexOf() is not added until Javascript Version 1.6 and IE 8 does not have built-in function for Array class. If the webpage is going to support IE 8 or belows, it would be better to add functions to Array's prototype as the followings:


if (!('indexOf' in Array.prototype)) {
    Array.prototype.indexOf = function(find, i /*opt*/) {
        if (i === undefined) i = 0;
        if (i < 0) i+= this.length;
        if (i < 0) i= 0;
        for (var n = this.length; i < n; i++)
            if (i in this && this[i]===find)
                return i;
        return -1;
    };
}

if (!('lastIndexOf' in Array.prototype)) {
    Array.prototype.lastIndexOf = function(find, i /*opt*/) {
        if (i === undefined) i = this.length-1;
        if (i < 0) i += this.length;
        if (i > this.length-1) i = this.length-1;
        for (i++; i-- > 0;) /* i++ because from-argument is sadly inclusive */
            if (i in this && this[i] === find)
                return i;
        return -1;
    };
}

In order to add this method compatibility to the IE 8 or belows, we need to add the above code to the Javascript declaration scope before any Array.indexOf() and Array.lastIndexOf() is begin called.

Just like this article does, check out the source of this page.

No comments:

Post a Comment