开发者

Define a multi dimensional array with javascript

I have this:

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

But I want to define the keys 开发者_JAVA百科for this array:

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

But that doesn't work. How is this done?


You wouldn't do this with array. What's called an associative array wikipedia in some languages is simply an object in JS. To declare an object with given properties, use an object literal:

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


There are two data structures in javascript, arrays and objects (actually, arrays are a special kind of object, but don't be concerned about that for now). An array is a collection with integer keys; the keys may be non-contiguous (i.e. they don't need to go 0,1,2,3, they might go 0,51,52,99,102). You can assign named properties to an array, but that makes iterating over them more difficult.

An object is a collection of arbitrarily-named keys that can be accessed very similarly to an array.

The simplest way to instantiate an array is as an array literal (which uses the square bracket notation), while the simplest way to create an object is with object literal (which uses curly-bracket notation):

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"
    }
}


You could perhaps try something of this approach:

    // 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

I hope this was of some help =).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜