How to assign multi dimensional array with key and values?

时间:2018-12-03 13:23:25

标签: javascript jquery

I'm declaring a multi dimensional array with key and values at jquery but its showing error here is my code:

var beadArray = 
 {
    0: {
    barCode: "843036905884",
    build: "144",
    height: "46",
    image: "https://www.brighton.com/charmbuilder/beads/v144_qijc0272.png",
    mask: [
            0: ["3", "36"],
            1: ["1", "38"],
            2: ["1", "38"],
            3: ["1", "38"],
            4: ["1", "37"],
            5: ["1", "37"],
            6: ["1", "37"],
            7: ["2", "37"],
            8: ["1", "38"]        
          ],
    name: "Autumn Spirit Bead",
    quantity: "484",
    rX: "19",
    rY: "23",
    retail: "29",
    style: "jc0272",
    theme: "A-E-H-I-J-L",
    type: "B",
    width: "40"
  }
};

its showing

Uncaught SyntaxError: Unexpected token : at 0: ["3", "36"], line

2 个答案:

答案 0 :(得分:1)

您不能使用数组中的索引定义值

var arr = [0:"1"];

您必须在如下所示的数组中设置值

var arr = ["1"];

您可以按原样访问

arr[0];

因此,您的语法应该是

var beadArray = 
 [
{
barCode: "843036905884",
build: "144",
height: "46",
image: "https://www.brighton.com/charmbuilder/beads/v144_qijc0272.png",
mask: [
         ["3", "36"],
         ["1", "38"],
         ["1", "38"],
         ["1", "38"],
         ["1", "37"],
         ["1", "37"],
         ["1", "37"],
         ["2", "37"],
         ["1", "38"]        
      ],
name: "Autumn Spirit Bead",
quantity: "484",
rX: "19",
rY: "23",
retail: "29",
style: "jc0272",
theme: "A-E-H-I-J-L",
type: "B",
width: "40"
  }
];

答案 1 :(得分:1)

Javascript没有关联数组,例如PHP中的数组怪物。它具有数组,并且具有与其他语言中的哈希或字典相似的对象文字。

要获取值列表时,应使用

Arrays

[1,2,3,4]

Object literals用于将键映射到值:

{ foo: 'bar' }

虽然您可以在对象文字中使用整数作为键,但在这种情况下它是毫无意义的

[
  ["3", "36"],
  ["1", "38"],
  ["1", "38"]
][1]

将给出与以下结果完全相同的结果:

{
    0: ["3", "36"],
    1: ["1", "38"],
    2: ["1", "38"]
}[1]