使用javascript定义多维数组

时间:2011-09-09 13:50:55

标签: javascript

我有这个:

var Test = new Array();
Test = ("Rose","India",564,375,new Array(5,6,7),".net");

但是我想定义这个数组的键:

Test = ("Rose" => "Pleb",
      "India" => "Test",
       564,
       375,
      new Array(5,6,7),
      ".net");

但这不起作用。这是怎么做到的?

3 个答案:

答案 0 :(得分:3)

你不会用数组做这个。在某些语言中,所谓的关联数组wikipedia只是JS中的一个对象。要声明具有给定属性的对象,请使用对象文字:

var Test = {
    Rose: "Pleb",
    India: "Test",
    'a-b': 'c,d',
    0: 564,
    1: 375,
    2: [5,6,7],
    3: ".net"
};

答案 1 :(得分:0)

javascript,数组和对象中有两种数据结构(实际上,数组是一种特殊的对象,但暂时不关心它)。数组是一个带整数键的集合;密钥可能是非连续的(即它们不需要去0,1,2,3,它们可能是0,51,52,99,102)。您可以将命名属性分配给数组,但这使得迭代它们变得更加困难。

对象是任意命名的键的集合,可以非常类似于数组访问。

实例化数组的最简单方法是作为数组文字(使用方括号表示法),而创建对象的最简单方法是使用object literal(使用花括号表示法):

var myArray = []; // creates a new empty array

var myOtherArray = [ "foo", "bar", "baz"]; // creates an array literal:
// myOtherArray[0] === "foo"
// myOtherArray[1] === "bar"
// myOtherArray[2] === "baz"
//

//
// This would be reasonably called a multidimensional array:
//
var myNestedArray = [ [ "foo", "bar", "baz"], [ "one", "two", "three"] ];
// myNestedArray[0] => [ "foo", "bar", "baz"];
// myNestedArray[1] => [ "one", "two", "three"];
// myNestedArray[0][0] === "foo";
// myNestedArray[1][0] === "one";

var myObject = {}; // creates an empty object literal

var myOtherObject = {
    one: "foo",
    two: "bar",
    three: "baz"
};
// myOtherObject.one === "foo"
// myOtherObject["one"] === "foo" (you can access using brackets as well)
// myOtherObject.two === "bar"
// myOtherObject.three === "baz"
//

//
// You can nest the two like this:
var myNestedObject = {
    anArray: [ "foo", "bar", "baz" ],
    anObject: {
        one: "foo",
        two: "bar",
        three: "baz"
    }
}

答案 2 :(得分:-1)

您也许可以尝试这种方法:

    // Declare an array to hold all of the data grid values
    var dataGridArray = [];

    // Turn dataGridArray into a 2D array
    for (arrayCounter = 0; arrayCounter < document.getElementById("cphMain_dtgTimesheet").rows.length - 2; arrayCounter++) {

        // Create a new array within the original array
        dataGridArray[arrayCounter] = [];

    } // for arrayCounter

我希望这有一些帮助=)。