我有一个这样的数组:
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(?);
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);
为了简单起见,我想用下面这个简单的例子来问这个问题:
function runcode(?){
console.log(array[0][1]); //which should return h.
}
runcode(?);
要访问a传递的变量,必须在函数头
中命名参数所以如果你用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)