【问题标题】:Array.prototype.forEach alternative implementation parametersArray.prototype.forEach 替代实现参数
【发布时间】:2011-12-02 05:59:28
【问题描述】:

在开发我最新的 Web 应用程序并需要使用 Array.forEach 函数时,我不断发现以下代码用于添加对没有内置该函数的旧浏览器的支持。

/**
 * 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);
            }
        }
    };
}

我完全理解代码的作用和工作原理,但我总是看到它复制了正式的 thisp 参数,注释掉了,而是使用 arguments[1] 将其设置为局部变量。

我想知道是否有人知道为什么要进行此更改,因为据我所知,如果将 thisp 作为形式参数而不是变量,该代码可以正常工作?

【问题讨论】:

    标签: javascript ecmascript-5


    【解决方案1】:

    Array.prototype.forEach.length 被定义为1,因此如果将它们的.length 属性也设置为1,实现函数会更像原生函数。

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

    forEach 方法的长度属性为 1。

    func.lengthfunc 基于其定义所采用的参数数量。)

    要使func.length 成为1,您必须将func 定义为仅接受1 个参数。在函数本身中,您始终可以使用arguments 获取所有参数。但是,通过将函数定义为采用 1 个参数,.length 属性为1。因此,根据规范更正确。

    【讨论】:

    • 嗯,有道理。我想知道为什么长度是1。我猜是因为第二个参数是可选的? (我从来不知道函数的长度就是参数的数量。整洁!)
    • @Joshua:可能吧,但不管规范是如何定义的,即使没有明确的原因:)
    【解决方案2】:

    这将遍历数组中的每个值,而不遍历原型函数等效的字符串。

    Array.prototype.forEach = function(fun /*, thisp*/) {
        if (typeof fun != "function") {
            throw new TypeError();
        }
    
        for(i = 0; i < this.length; i++){
            ...
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-29
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-25
      • 1970-01-01
      • 2013-10-27
      • 2020-10-10
      相关资源
      最近更新 更多