Implementation of ECMAScript5 added Array method (Continued)

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Preface

Following a talk about the forEach iterative method ES5 added Array, analysis of the iterative method of today: map, filter, every, some. The role of these methods are as follows:

Note: the above method will not modify the value of contained in the array, and these methods, the most similar are every and some, which are used to query the array of items whether a condition is met. For every, the incoming function to each return true, this method returns true. And the some method is as long as the incoming function on an array of a return to the true, it will return true.


Using the example

var numbers = [1, 2, 3, 4, 5];
// The map method returns a new array, each of the new array is in the original array, the corresponding entry in the running result of afferent function
console.log(numbers.map(function(item, index, array) {
    return item * 2; // [2, 4, 6, 8, 10]
}));
// The filer method -- Query array eligible
console.log(numbers.filter(function(item, index, array) {
    return (item > 2); // [3, 4, 5]
}));
// The every method
console.log(numbers.every(function(item, index, array) {
    return (item > 2); // false
}));
// The some method
console.log(numbers.some(function(item, index, array) {
    return (item > 2); // true
}));

The test results under Firefox:

The above is only some simple examples, and optional parameters ( domain object ) has no incoming. Although the use of these methods in some cases array processing task is easy, but the support of these iterative methods browser only IE9+, Firefox 2+, Safari 3+, Opera 9.5+ and Chrome. So in order to be compatible with an IE6+, we have to deal with some compatibility, can the Array prototype is extended, the method is extended for most web browsers, and the effect is similar to the new ES5 iterative method.


The prototype Array extension

How to extend these methods and these methods in the Array prototype is what are the specific parameters will not say more, can achieve a forEach method to find the previous blog. The following one by one to achieve:

1,map: The method can be understood as maps , namely the original array is “ &rdquo mapping; a new array corresponding.

Realization of the code:

/**
 * map
 * @param {Function}  The callback function
 * @param {Object} Scope object (environment)
 * @return {Array} The new array
 */
if (!Array.prototype.map && typeof Array.prototype.map !== "function") {
     Array.prototype.map = function(callback, context) {
        // Traversing arrays, the callback function is invoked in each item, the primary method is used here to verify array. 
        if (Object.prototype.toString.call(this) === "[object Array]") {
            var i,
                len,
                arr = [];
                if (typeof callback === "function") {
                    for (i = 0, len = this.length; i <len; i++) {
                        arr.push(callback.call(context, this[i], i, this));
                    }
                }
                
            return arr; // Returns an array of matching
        }
     };
}

The demo sample (has passed, all browser testing including IE6+):

// The map method in Listing 1
var mapResult1 = [1, 2, 3, 4].map(function(value, index, array) {
    return value * value;
});
alert(mapResult1); // [1, 4, 9, 16]

// Map method for example 2- afferent function domain object context
var data = {
    numbers: [1, 2, 3, 4],
    getNumber: function(value, index, array) {
        return value * value;
    }
};
var mapResult2 = data.numbers.map(data.getNumber, data);
alert(mapResult2); // [1, 4, 9, 16]


2,filter: The method can be understood as the filter or screening of , a new array is returned after filtering. Usage is very similar with map.

Realization of the code:

/**
 * Filter-- is used to filter array of items, and returns a new array. 
 * @param {Function}  The callback function
 * @param {Object} Scope object (environment)
 * @return {Array} The new array
 */
if (!Array.prototype.filter && typeof Array.prototype.filter !== "function") {
     Array.prototype.filter = function(callback, context) {
        // Traversing arrays, the callback function is invoked in each item, the primary method is used here to verify array. 
        if (Object.prototype.toString.call(this) === "[object Array]") {
            var i,
                len,
                arr = [];
                if (typeof callback === "function") {
                    for (i = 0, len = this.length; i <len; i++) {
                        // The item is added to the array of matching
                        callback.call(context, this[i], i, this) && arr.push(this[i]);
                    }
                }
                
            return arr; // Return a new array
        }
     };
}

The demo sample (has passed, all browser testing including IE6+):

// The filter method in Listing 1
var filterResult1 = [1, 2, 3, 4].filter(function(value, index, array) {
    return (value > 2);
});
alert(filterResult1); // [3, 4]

// Filter method for example 2- afferent function domain object context
var data = {
    numbers: [1, 2, 3, 4],
    getNumber: function(value, index, array) {
        return (value > 2);
    }
};
var filterResult2 = data.numbers.filter(data.getNumber, data);
alert(filterResult2); // [3, 4]

Such as FF under the test results.:


3,every: The method for each operation of a given function in an array, if the function of each return true, otherwise it returns true.

 Realization of the code:

/**
 * every
 * @param {Function}  The callback function
 * @param {Object} Scope object (environment)
 * @return {Boolean} true || false
 */
if (!Array.prototype.every && typeof Array.prototype.every !== "function") {
     Array.prototype.every = function(callback, context) {
        // Traversing arrays, the callback function is invoked in each item, the primary method is used here to verify array. 
        if (Object.prototype.toString.call(this) === "[object Array]") {
            var i,
                len,
                isRight = true; // By default, all array operation given function for true
                
                if (typeof callback === "function") {
                    for (i = 0, len = this.length; i <len; i++) {
                        if (isRight === false) {
                            break; // Out of the loop, termination of execution
                        } else {
                            isRight = Boolean(callback.call(context, this[i], i, this));
                        }
                    }
                }
                
            return isRight; // Returns the value of Boolean
        }
     };
}

The demo sample (has passed, all browser testing including IE6+):

// The every method in Listing 1
var everyResult1 = [1, 2, 3, 4].every(function(value, index, array) {
    return (value > 2);
});
alert(everyResult1); // false

// Every method for example 2- afferent function domain object context
var data = {
    numbers: [1, 2, 3, 4],
    getNumber: function(value, index, array) {
        return (value > 2);
    }
};
var everyResult2 = data.numbers.every(data.getNumber, data);
alert(everyResult2); // false

4,some: The method for each operation in an array of a given function, if this function returns true on any one, true is returned; otherwise it returns false.

To achieve consistent principle and every, only value can be modified with a variable isRight, the JS code is as follows:

/**
 * some
 * @param {Function}  The callback function
 * @param {Object} Scope object (environment)
 * @return {Boolean} true || false
 */
if (!Array.prototype.some && typeof Array.prototype.some !== "function") {
     Array.prototype.some = function(callback, context) {
        // Traversing arrays, the callback function is invoked in each item, the primary method is used here to verify array. 
        if (Object.prototype.toString.call(this) === "[object Array]") {
            var i,
                len,
                isRight = false; // By default, all array operation given function for false
                
                if (typeof callback === "function") {
                    for (i = 0, len = this.length; i <len; i++) {
                        if (isRight === true) {
                            break; // Out of the loop, termination of execution
                        } else {
                            isRight = Boolean(callback.call(context, this[i], i, this));
                        }
                    }
                }
                
            return isRight; // Returns the value of Boolean
        }
     };
}

The demo sample (has passed, all browser testing including IE6+):

// The some method in Listing 1
var someResult1 = [1, 2, 3, 4].some(function(value, index, array) {
    return (value > 2);
});
alert(someResult1); // true

// Every method for example 2- afferent function domain object context
var data = {
    numbers: [1, 2, 3, 4],
    getNumber: function(value, index, array) {
        return (value > 2);
    }
};
var someResult2 = data.numbers.some(data.getNumber, data);
alert(someResult2); // true

Shout (~ o ~ ~zZ), finally the test finished, fuck, the sun fell mountain. Examples are the same, the key is to achieve idea understand was not very difficult. Also worth noting: parameter calls these methods as well as the meaning of the order.


Conclusion

 The iterative method of ES5 new array of the corresponding expansion, is when these methods are used, without considering the compatibility issues, of course, does not take into account the code performance. Call it a day, have questions or suggestions welcome troops comments. PS: recently about the examination, blog for a period of time have no time to write it., ╮(╯▽╰)╭.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Ivan at November 13, 2013 - 10:00 PM