在javascript中使用自定义索引的多维数组

时间:2021-06-24 21:31:41

How can I make multidimensional array in javascript in the following format:

如何在javascript中以下列格式制作多维数组:

Array[

{index}:{x-coords}
        {y-coords},

{index2}:{x-coords}
        {y-coords},
.... ];

The data should look like as follows:

数据应如下所示:

Array[
{
indexabc:{10},{20}
},
{
indexxyz:{30},{40}
}
];

Also, how to access the array elements? I am storing value in them through a function so it will be called recursively.

另外,如何访问数组元素?我通过函数将值存储在它们中,因此它将被递归调用。

3 个解决方案

#1


1  

var arr = [[x-coords, y-coords], [x-coords, y-coords]...]

is a multidimensional array, however if you want key - value pairs, you might want to use an object

是一个多维数组,但是如果你想要键 - 值对,你可能想要使用一个对象

var obj = {
    index: [x-coords, y-coords],
    index2: [x-coords, y-coords],
    ...
}

to fit your data either use William B's answer or something like that

为了适应你的数据要么使用William B的答案,要么使用类似的东西

var obj = {
    indexabc: [10, 20],
    indexxyz: [30, 40]
}

so you can access data like so

所以你可以像这样访问数据

obj.indexabc[0]

#2


4  

It sounds like you want plain old Object:

听起来你想要普通的旧对象:

var o = {
  indexabc: { x: 10, y: 20},
  indexxyz: { x: 30, y: 40 }
};

console.log( o.indexabc.x, o.indexabc.y );

#3


3  

If you just want to create a two-dimensional array you can easy do like that:

如果您只想创建一个二维数组,您可以轻松地执行以下操作:

var a = [];
a[0] = [1,2];
a[1] = [2,3];
console.log(a[0]) // [1,2]

#1


1  

var arr = [[x-coords, y-coords], [x-coords, y-coords]...]

is a multidimensional array, however if you want key - value pairs, you might want to use an object

是一个多维数组,但是如果你想要键 - 值对,你可能想要使用一个对象

var obj = {
    index: [x-coords, y-coords],
    index2: [x-coords, y-coords],
    ...
}

to fit your data either use William B's answer or something like that

为了适应你的数据要么使用William B的答案,要么使用类似的东西

var obj = {
    indexabc: [10, 20],
    indexxyz: [30, 40]
}

so you can access data like so

所以你可以像这样访问数据

obj.indexabc[0]

#2


4  

It sounds like you want plain old Object:

听起来你想要普通的旧对象:

var o = {
  indexabc: { x: 10, y: 20},
  indexxyz: { x: 30, y: 40 }
};

console.log( o.indexabc.x, o.indexabc.y );

#3


3  

If you just want to create a two-dimensional array you can easy do like that:

如果您只想创建一个二维数组,您可以轻松地执行以下操作:

var a = [];
a[0] = [1,2];
a[1] = [2,3];
console.log(a[0]) // [1,2]