Array.prototype.forEach alternative implementation parameters

主宰稳场 提交于 2019-12-05 00:55:39

问题


When working on my latest web application and needing to use the Array.forEach function, I constantly found the following code used to add support to older browsers that do not have the function built in.

/**
 * Copyright (c) Mozilla Foundation http://www.mozilla.org/
 * This code is available under the terms of the MIT License
 */
if (!Array.prototype.forEach) {
    Array.prototype.forEach = function(fun /*, thisp*/) {
        var len = this.length >>> 0;
        if (typeof fun != "function") {
            throw new TypeError();
        }

        var thisp = arguments[1];
        for (var i = 0; i < len; i++) {
            if (i in this) {
                fun.call(thisp, this[i], i, this);
            }
        }
    };
}

I fully understand what the code does and how it works, but I always see it copied with the formal thisp parameter commented out and having it be set as a local variable using arguments[1] instead.

I was wondering if anyone knew why this change was made, because from what I can tell, the code would have worked fine with thisp as a formal parameter rather than a variable?


回答1:


Array.prototype.forEach.length is defined as 1, so implementation functions would be more native-like if they had their .length property set to 1 too.

http://es5.github.com/#x15.4.4.18

The length property of the forEach method is 1.

(func.length is the amount of argument that func takes based on its definition.)

For func.length to be 1, you have to define func to only take 1 argument. In the function itself you can always get all arguments with arguments. However, by defining the function to take 1 argument, the .length property is 1. Therefore, it is more correct according to the specification.




回答2:


This will iterate through each of the values in the array without iterating over the string equivalent of prototype functions.

Array.prototype.forEach = function(fun /*, thisp*/) {
    if (typeof fun != "function") {
        throw new TypeError();
    }

    for(i = 0; i < this.length; i++){
        ...
    }

}


来源:https://stackoverflow.com/questions/8348569/array-prototype-foreach-alternative-implementation-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!