如何在数组中,在另一个数组中访问数组中的元素...在JavaScript中

时间:2012-10-04 21:52:34

标签: javascript arrays

我正在尝试调用数组中的元素,即另一个数组中的另一个数组。 例如....

  var a1 = ["1","2","3"];
  var a2 = ["4","5","6"];
  var a3 = ["7","8","9"];
  var a4 = ["10","11","12"];

  var b1 = ["a1","a2"];
  var b2 = ["a3","a4"];

  var c = ["b1","b2"];

  var x = c[0];

  console.log(x);

答案是x = b1

如何定义var x = c[0] b1[1] a2[2]以便答案为6?

4 个答案:

答案 0 :(得分:0)

将数组定义为其他数组的元素,而不是字符串:

var a1 = [1, 2, 3];
...
var b1 = [a1, a2];
...
var c = [b1, b2];

var x = c[0][0][0]; // 1

答案 1 :(得分:0)

数组a1实际上不在b1中 - 只有一个包含文本“a1”的字符串。如果你这样定义它们:

var a1 = ["1","2","3"];
var a2 = ["4","5","6"];
var a3 = ["7","8","9"];
var a4 = ["10","11","12"];

var b1 = [a1, a2];
var b2 = [a3, a4];

var c = [b1, b2];

然后你可以写c[0][1][2]来获得“6”。

答案 2 :(得分:0)

你想要的是嵌套数组。

var a1 = ["1","2","3"];
var a2 = ["4","5","6"];
var a3 = ["7","8","9"];
var a4 = ["10","11","12"];

var b1 = [a1,a2];
var b2 = [a3,a4];

var c = [b1,b2];

var x = c[0][1][2];

console.log(x);

答案 3 :(得分:0)

var a1 = ["1","2","3"], a2 = ["4","5","6"], a3 = ["7","8","9"], a4 = ["10","11","12"];
var b1 = [a1,a2];
var b2 = [a3,a4];
var c = [b1,b2];

var x1 = c[0][0][0];
var x2 = c[0][0][1];
var x3 = c[0][0][2];

console.log(x1); //1 (1st/0 item of a1) from c
console.log(x2); //2 (2nd/1 item of a1) from c
console.log(x3); //3 (3rd/2 item of a1) from c

DEMO