Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Array.prototype.forEach替代实现参数_Javascript_Ecmascript 5 - Fatal编程技术网

Javascript Array.prototype.forEach替代实现参数

Javascript Array.prototype.forEach替代实现参数,javascript,ecmascript-5,Javascript,Ecmascript 5,在处理我最新的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.forE

在处理我最新的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);
            }
        }
    };
}
/**
* Copyright(C)Mozilla基金会http://www.mozilla.org/
*此代码在MIT许可证的条款下可用
*/
if(!Array.prototype.forEach){
Array.prototype.forEach=函数(fun/*,thisp*/){
var len=this.length>>>0;
如果(乐趣的类型!=“功能”){
抛出新的TypeError();
}
var thisp=参数[1];
对于(变量i=0;i
我完全理解代码的功能和工作方式,但我总是看到它被正式的
thisp
参数注释掉,并使用
参数[1]
将其设置为局部变量


我想知道是否有人知道为什么会做出这样的更改,因为据我所知,如果将
thisp
作为一个形式参数而不是一个变量,代码会很好地工作?

Array.prototype.forEach.length
定义为
1
,因此,如果实现函数的
.length
属性也设置为
1
,则实现函数更像是本机函数

forEach方法的length属性为1

func.length
func
根据其定义获取的参数量。)


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

这将迭代数组中的每个值,而不会迭代原型函数的字符串等价物

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

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

}
Array.prototype.forEach=函数(fun/*,thisp*/){
如果(乐趣的类型!=“功能”){
抛出新的TypeError();
}
对于(i=0;i
Hmm,有道理。我想知道为什么长度是1。我猜这是因为第二个参数是可选的?(我从来不知道函数的长度是参数的数量。很好!)@Joshua:可能吧,但不管规范怎么说,它都是如何定义的,即使没有明确的理由:)