Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.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数组,其中每个元素都有一个函数,可以引用其在新数组中的位置_Javascript - Fatal编程技术网

创建javascript数组,其中每个元素都有一个函数,可以引用其在新数组中的位置

创建javascript数组,其中每个元素都有一个函数,可以引用其在新数组中的位置,javascript,Javascript,我试图获取一个字符串数组,并使用它们根据这些字符串的过滤子集创建一个对象数组。我需要我的对象包含一个方法,该方法可以访问所创建数组中该对象的位置 我尝试了以下方法: var strings = ["one", "two", "three"]; var created = []; var index = 0; jQuery.each(strings, function( i, item) { if( /*some condition about item*/ ) { c

我试图获取一个字符串数组,并使用它们根据这些字符串的过滤子集创建一个对象数组。我需要我的对象包含一个方法,该方法可以访问所创建数组中该对象的位置

我尝试了以下方法:

var strings = ["one", "two", "three"];
var created = [];

var index = 0;

jQuery.each(strings, function( i, item) {
    if( /*some condition about item*/ ) {
        created.push(
            {
                myMethod: function() {
                    callSomething(index);
                }
            }
        );
        index++;
    }
});
但明显的问题是,
index
是一个变量,因此对
callSomething
的任何调用都只会传递其当前值。我希望
callSomething
callSomething
定义时传递
index
的值


我不能只使用jQuery中的索引(
I
),因为我不希望所有元素都出现在新数组中,只是一个筛选集。

由于原语类型作为值传递给函数,因此可以使用即时函数调用来声明这些函数,例如:

var strings = ["one", "two", "three"];
var created = [];

var index = 0;

jQuery.each(strings, function( i, item) {
    if( /*some condition about item*/ ) {
        created.push(
            {
                myMethod: (function(idx) {
                    return function() {
                      callSomething(idx);
                    }
                })(index)
            }
        );
        index++;
    }
});

由于原语类型作为值传递给函数,因此可以使用即时函数调用声明这些函数,例如:

var strings = ["one", "two", "three"];
var created = [];

var index = 0;

jQuery.each(strings, function( i, item) {
    if( /*some condition about item*/ ) {
        created.push(
            {
                myMethod: (function(idx) {
                    return function() {
                      callSomething(idx);
                    }
                })(index)
            }
        );
        index++;
    }
});

created.push(…)
调用之前使用
const index=created.length
-通过在循环中声明变量,闭包将使用正确的值在
created.push(…)
调用之前使用
const index=created.length
-通过在循环中声明变量,您的闭包将使用正确的值