带有字母数字键的 Javascript 多维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16266495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:58:53  来源:igfitidea点击:

Javascript multidimensional arrays with alphanumeric keys

javascriptarraysobjectmultidimensional-array

提问by Chuck Le Butt

This seems to be a common source of confusion from what I've seen, and apparently I'm no exception. I've read a few tutorials on this, and I still can't quite get my head around it. From what I can gather, Arrays are objects in Javascript, just like Strings and other variable types. But I still don't get how that helps me declare a multidimensional array with alphanumeric keys.

这似乎是我所看到的常见混淆来源,显然我也不例外。我已经阅读了一些关于此的教程,但我仍然无法完全理解它。据我所知,数组是 Javascript 中的对象,就像字符串和其他变量类型一样。但是我仍然不明白这如何帮助我声明一个带有字母数字键的多维数组。

In PHP I can simply write:

在 PHP 中,我可以简单地写:

$calendar = array();

foreach ($schedule->currentExhibitions as $key) {
    $calendar[$key["ExhibitionID"]]["startDate"] = date("Y,n,j", strtotime($exhibition["StartDate"]));
    $calendar[$key["ExhibitionID"]]["endDate"] = date("Y,n,j", strtotime($exhibition["StartDate"]));
} 

But in Javascript trying something similar will create errors. Should I create an Array and fill it will Objects? If so, how would I go about doing so? Or should I just use an Object entirely and skip having any sort of Array? (If so, how do I create a multidimensional Object?)

但是在 Javascript 中尝试类似的东西会产生错误。我应该创建一个数组并填充它吗?如果是这样,我将如何去做?或者我应该完全使用一个对象并跳过任何类型的数组?(如果是这样,我如何创建一个多维对象?)

Sorry for the newbish quesion!

对不起,新手问题!

采纳答案by Alan

In Javascript, an array is an object, who's keys are numerical, sequential, indexes.

在 Javascript 中,数组是一个对象,其键是数字、顺序、索引。

As soon as you want to use alpha-numerica (aka strings) keys, you use a regular object.

只要您想使用字母数字(又名字符串)键,就可以使用常规对象。

In JS to do what you want, you'd do the following (using more or less your php code).

在 JS 中做你想做的事,你会做以下(或多或少使用你的 php 代码)。

var calendar = {};

Object.keys(schedule.currentExhibitions).forEach(function(key) {
  var ex = schedule.currentExhibitions[key];

  calendar[ex.exhibitionId] = calendar[ex.exhibitionId] || {}; //if the key doesn't exist, create it.
  calendar[ex.exhibitionId].startDate = date(); //some js date function here
  calendar[ex.exhibitionId].endDate = date(); //your js date function here
});

回答by David McMullin

If your keys are strictly numerical and ordered starting at zero, then an array makes sense and you can use square bracket notation just like you would in php, although you will need to initialize sub-arrays if you want to have multiple dimensions :

如果您的键是严格的数字并且从零开始排序,那么数组是有意义的,您可以像在 php 中一样使用方括号表示法,但如果您想拥有多个维度,则需要初始化子数组:

var myArray = [];
myArray[0] = [];
myArray[0][0] = "something interesting";

If your keys are not numerical, ordered and starting at zero, then you should use an object (all keys are strings), which still allows the square bracket notation :

如果您的键不是数字、有序且从零开始,那么您应该使用一个对象(所有键都是字符串),它仍然允许方括号表示法:

var myObject = {};
myObject["1A"] = {};
myObject["1A"]["3B"] = "something interesting";

回答by Travis J

I look at Multidimension as nesting, and at multiple levels of nestings as complex objects. For example:

我将多维视为嵌套,将多层嵌套视为复杂对象。例如:

var parent = [];//top holder
var child1 = {};
child1.name = "Jim";
parent.push(child1);

In this simple example, you can access child1 like this:

在这个简单的例子中,你可以像这样访问 child1:

parent[0]["name"] //Jim

So that is, in a way, multidemensional. Instead of using ["name"]as an indexer, or child1as an object it could also be an array, like this:

所以,在某种程度上,这是多维的。它也可以是一个数组,而不是["name"]用作索引器或child1对象,如下所示:

var parent = [];//top holder
var child1 = [];
child1.push("Jim");
parent.push(child1);

In this example, you could get Jim with:

在这个例子中,你可以得到 Jim:

parent[0][0];//Jim

So for complex examples you may have multiple levels of these nestings (or dimensions).

因此,对于复杂的示例,您可能有多个级别的这些嵌套(或维度)。

parent[0]["Child"].grandChild[5]["cousin"].name //etc

Where that would just be a continuation of the previous examples down the line.

这只是前面例子的延续。

回答by jfriend00

If you want to preserve order or you want to access by numeric index, use an array. The value of the array can be a single value or an object or array itself (so each value in the array can contain more than a simple value).

如果要保留顺序或要按数字索引访问,请使用数组。数组的值可以是单个值,也可以是对象或数组本身(因此数组中的每个值可以包含多个简单值)。

If you want to access by a unique alphanumeric key, then use an object and assign properties to it.

如果要通过唯一的字母数字键访问,请使用对象并为其分配属性。

Arrays have numeric indexes. They do not have alphanumeric indexes.

数组具有数字索引。它们没有字母数字索引。

Objects have string keys.

对象具有字符串键。

Because an array is also an object, it can have both types of keys, but using a string key is not an array access, it's accessing a property of the object.

因为数组也是一个对象,所以它可以有两种类型的键,但使用字符串键不是数组访问,它是访问对象的属性。

When you ask for the .lengthof an array, you only get the length of the numeric indexes. It does not include other properties of the object.

当您要求.length数组的 时,您只能获得数字索引的长度。它不包括对象的其他属性。

An array of objects is a very practical data structure in javascript and is used quite often when either order or index by numeric index is important.

对象数组是 JavaScript 中一种非常实用的数据结构,当顺序或数字索引很重要时经常使用它。

If order is not important or you don't need to access by numeric index and just want to access by an alpha numeric string, then you should just use an object and set a properties on it with keys that are your alphanumeric string.

如果顺序不重要,或者您不需要通过数字索引访问而只想通过字母数字字符串访问,那么您应该只使用一个对象并使用作为您的字母数字字符串的键在其上设置属性。