用javascript定义一个多维数组

Define a multi dimensional array with javascript

本文关键字:一个 数组 javascript 定义      更新时间:2023-09-26

我有这个:

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");

但这不起作用。这是如何做到的呢?

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

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

在javascript中有两种数据结构,数组和对象(实际上,数组是一种特殊的对象,但现在不用担心)。数组是具有整型键的集合;键可能是不连续的(即它们不需要去0、1、2、3,它们可能去0、51、52、99、102)。你可以给数组分配命名属性,但这会使遍历它们变得更加困难。

对象是一组任意命名的键的集合,可以像访问数组一样访问它们。

实例化数组的最简单方法是使用数组文字(使用方括号符号),而创建对象的最简单方法是使用对象文字(使用大括号符号):

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

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

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