Array.prototype.forEach alternative implementation parameters

微笑、不失礼 提交于 2019-12-03 16:28:03

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.

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++){
        ...
    }

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