1

我有一个这样的数组:

var array = [['h','e','l','l','o'],['1','2','3','4','5'],['a','b','c','d','e']]

我无法将它传递给函数这是我正在使用的原始脚本:

for (var x = 0; x <= 2; x++) {
    var timesrun = 0;

    function runcode() {
        timesrun += 1;
        for (var n = 0; n <= 4; n++) {
            console.log(array[x][n]);
        } //end for loop 1
        if (timesrun == 2) {
            clearInterval(interval);
        }
    } //end of function
} // end for loop 2
var interval = setInterval(function () {
    runcode(array[x]);
}, 1000);

当我console.log在函数内部时,我什么也得不到,但是如果我将内部for循环置于函数外部,然后console.log得到预期值,所以我认为我没有正确地将值带入函数中。

为简单起见,我想使用下面的简单示例来问这个问题:

function runcode(?){
    console.log(array[0][1]);  //which should return h.
}
runcode(?);
4

2 回答 2

1
var array = [['h','e','l','l','o'],['1','2','3','4','5'],['a','b','c','d','e']],
    x = 0,
    timesrun = 0;

function runcode() {
    timesrun += 1;
    for (var n = 0; n <= 4; n++) {
        console.log(array[x][n]);
    }
    if (timesrun == 2) {
        clearInterval(interval);
    }
}    

var interval = setInterval(function () {
    for (x = 0; x <= 2; x++) {
        runcode(array[x]);
    }
}, 1000);
于 2013-04-24T08:52:05.597 回答
0

为简单起见,我想使用下面的简单示例来问这个问题:

function runcode(?){
    console.log(array[0][1]);  //which should return h.
}

runcode(?);

要访问传递的变量,您必须在函数头中命名参数

所以如果你愿意替换?array已经很好了

function runcode(array){
              // ^^^^^ This is the name under which you can acces the passed variable
    console.log(array[0][1]);  //which should return h.
              //^^^^^ This is where you use it

}
runcode(array);
      //^^^^^ this is where you pass it //could be someOther2DimensionalArray

并应用于非工作代码

var array = [
    ['h', 'e', 'l', 'l', 'o'],
    ['1', '2', '3', '4', '5'],
    ['a', 'b', 'c', 'd', 'e']
],
    x = 0,
    timesrun = ~0;

function runcode(array) {
    x = timesrun += 1;
    for (var n = 0; n <= 4; n++) {
        console.log(array[x][n]);
    }
    if (timesrun == 2) {
        clearInterval(interval);
    }
}

var interval = setInterval(runcode, 1000, array);

这应该可以解决问题。

注意第三个参数setInterval是用来传递array//runcode(array)

于 2013-04-25T15:07:26.333 回答