1

我看到一些关于 jQuery 缺少可变变量(如 php)的帖子,我想知道如何处理这种情况?当我想使用变量“i”来选择一个数组时。

var arr1_1 = ["1","1","1","0","0","0","0","0","0"];
var arr1_2 = ["1","0","0","0","1","0","0","0","1"];
var arr1_3 = ["0","0","0","1","1","1","0","0","0"];
var arr1_4 = ["0","0","0","0","0","0","1","1","1"];
var arr1_5 = ["0","0","1","0","1","0","1","0","0"];
var arr1_6 = ["1","0","0","1","0","0","1","0","0"];
var arr1_7 = ["0","1","0","0","1","0","0","1","0"];
var arr1_8 = ["0","0","1","0","0","1","0","0","1"];

for(var i=0; i <= 9; i++){
    console.log(
        arr1_"here is the i";
    )
}
4

4 回答 4

2

将其存储为哈希是一个更好的主意,因为您的数据将被结构化。

var data = {
    "arr1_1": ["1", "1", "1", "0", "0", "0", "0", "0", "0"],
    "arr1_2": ["1", "0", "0", "0", "1", "0", "0", "0", "1"],
    "arr1_3": ["0", "0", "0", "1", "1", "1", "0", "0", "0"],
    "arr1_4": ["0", "0", "0", "0", "0", "0", "1", "1", "1"],
    "arr1_5": ["0", "0", "1", "0", "1", "0", "1", "0", "0"],
    "arr1_6": ["1", "0", "0", "1", "0", "0", "1", "0", "0"],
    "arr1_7": ["0", "1", "0", "0", "1", "0", "0", "1", "0"],
    "arr1_8": ["0", "0", "1", "0", "0", "1", "0", "0", "1"],
}

for(var i=0; i <= 9; i++){
   console.log(
       data["arr1_" + i]
   )
}

检查小提琴

于 2013-07-15T18:33:01.913 回答
1

我相信您可以使用该eval功能实现您想要做的事情

for(var i=0; i <= 9; i++){
    console.log(
        'here is the arr1_'+i+': ' + eval('arr1_'+i);
    )
}
于 2013-07-15T18:26:24.690 回答
0

您可以通过 JavaScript 中的括号运算符检索变量:

for(var i=0; i <= 9; i++) {
  var varName = 'arr1_'+(i+1);
  console.log(window[varName]);
}

假设您的数组变量在“窗口”范围内。

于 2013-07-15T18:28:31.090 回答
0

我会使用一组数组:

var arr = [
    [] /* 0th index - confused about your example - start with 1? */
    ,["1","1","1","0","0","0","0","0","0"]
    ,["1","0","0","0","1","0","0","0","1"]
    ,["0","0","0","1","1","1","0","0","0"]
    ,["0","0","0","0","0","0","1","1","1"]
    ,["0","0","1","0","1","0","1","0","0"]
    ,["1","0","0","1","0","0","1","0","0"]
    ,["0","1","0","0","1","0","0","1","0"]
    ,["0","0","1","0","0","1","0","0","1"]
];

for(var i=0; i <= 9; i++) {
    console.log(arr[i]);
}

然后,您可以访问单个成员

arr[row][col];
于 2013-07-15T18:34:18.393 回答