Javascript javascript多维数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2529865/
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-08-23 00:46:35  来源:igfitidea点击:

javascript multidimensional array?

javascriptarrays

提问by Megapool020

I hope I can make myself clear in English and in what I want to create. I first start with what I want.

我希望我能用英语和我想创造的东西说清楚。我首先从我想要的开始。

I want to make a IBANcalculator that can generate 1-n IBANnumbers and also validate a given IBANnumber. IBANnumbers are used in many countries for payment and the tool I want to make can be used to generate the numbers for testing purpose.

我想制作一个可以生成 1-n 个 IBANnumbers 并验证给定 IBANnumber 的 IBANcalculator。许多国家/地区都使用 IBANnumbers 进行支付,我想制作的工具可用于生成数字以进行测试。

On wikipedia(Dutch site) I found a list with countries and their way of defining the IBANnumber. What I want to do it to make a kind of an array that holds all the countries with their name, the code, there IBANlength, the bankingformat and the account format.

维基百科(荷兰网站)上,我找到了一个包含国家和他们定义 IBAN 号码的方式的列表。我想要做的是制作一种数组,其中包含所有国家的名称、代码、IBAN 长度、银行格式和帐户格式。

The array needs to be used to:

该数组需要用于:

  1. Generate a select list (for selecting a country)
  2. used to check part for generating numbers
  3. used to check part for validating number
  1. 生成选择列表(用于选择国家/地区)
  2. 用于检查生成数字的部分
  3. 用于检查验证号码的部分

I don't know if an array is the best way, but that's so far the most knowledge I have.

我不知道数组是否是最好的方法,但这是迄今为止我所拥有的最多知识。

I allready made a table like this that holds the info (this table isn't used anyware, but it was a good way for me to show you what I have in mind about how the structure is):

我已经制作了一个这样的表格来保存信息(这个表格在任何情况下都没有使用,但它是我向您展示我对结构的看法的好方法):

<table>
 <tr>
  <td>countryname</td>
  <td>country code</td>
  <td>valid IBAN length</td>
  <td>Bank/Branch Code (check1, bank, branch)</td>
  <td>Account Number (check2, number, check3)</td>
 <tr>
 <tr>
  <td>Andorra</td>
  <td>AD</td>
  <td>24</td>
  <td>0  4n 4n</td>
  <td>0  12   0 </td>
 <tr>
 <tr>
  <td>Belgi?</td>
  <td>BE</td>
  <td>16</td>
  <td>0  3n 0 </td>
  <td>0   7n  2n</td>
 <tr>
 <tr>
  <td>Bosni?-Herzegovina</td>
  <td>BA</td>
  <td>20</td>
  <td>0  3n 3n</td>
  <td>0   8n  2n</td>
 <tr>
</table>

and many more.

还有很多。

回答by T.J. Crowder

The main answer

主要答案

I wouldn't use an "array" for this at all. JavaScript objects are maps (sometimes called "associative arrays," but let's use "map" to avoid confusion with numerically-indexed arrays), so you can do this with plain objects quite easily:

我根本不会为此使用“数组”。JavaScript 对象是映射(有时称为“关联数组”,但让我们使用“映射”来避免与数字索引数组混淆),因此您可以很容易地对普通对象执行此操作:

var IBANInfo = {
    "AD": {
        countryCode: "AD",
        countryName: "Andorra",
        length: 24,
        bankBranchCode: "0  4n 4n",
        accountNum: "0  12   0"
    },
    "BE": {
        countryCode: "BE",
        countryName: "Belgi\u00EB",
        length: 16,
        bankBranchCode: "0  3n 0",
        accountNum: "0  7n   2n"
    },
    "BA": {
        countryCode: "BA",
        countryName: "Bosni\u00EB-Herzegovina",
        length: 20,
        bankBranchCode: "0  3n 3n",
        accountNum: "0   8n  2n"
    }
};

(Note that I've used the Unicode escape for the 'e' with the umlaut above it; probably for the best, although if you're careful with your encodings you should be fine.)

(请注意,我已经将 Unicode 转义用于 'e' 上面的变音符号;可能是最好的,尽管如果您对编码很小心,应该没问题。)

That uses object literal notation to create the individual objects and the overall map. In the overall map, there is a property for each country, with the property key being the country code and the property value being an object providing the information from your table.

它使用对象文字符号来创建单个对象和整个地图。在整个地图中,每个国家都有一个属性,属性键是国家代码,属性值是提供表中信息的对象。

You can then look up a country's information in the map using its country code like this:

然后,您可以使用其国家/地区代码在地图中查找该国家/地区的信息,如下所示:

var countryInfo = IBANInfo["AD"]; // <= Example for Andorra

Or if you have the country code in another variable:

或者,如果您在另一个变量中有国家/地区代码:

var countryCode = "AD"; // <= Example for Andorra
var countryInfo = IBANInfo[countryCode];
alert("Country name: " + countryInfo.countryName); // <= Alerts "Country name: Andorra"

Obviously if you prefer to look up by something other than country code, just adjust things accordingly.

显然,如果您更喜欢按国家/地区代码以外的内容查找,只需相应地调整即可。

Putting a prefix on keys out of paranoia

出于偏执,在键上加上前缀

When doing this with information I have little control over, I usually put a prefix on the key to avoid running into issues with conflicts with the built-in properties of an object (although I don't think there's much likelihood of conflict here). If you used a "cc" prefix, for instance, things would look like this:

当使用我几乎无法控制的信息执行此操作时,我通常在键上添加前缀,以避免遇到与对象的内置属性冲突的问题(尽管我认为这里不太可能发生冲突)。例如,如果您使用“cc”前缀,事情将如下所示:

The map:

地图:

var IBANInfo = {
    "ccAD": {
        countryCode: "AD",
        countryName: "Andorra",
        length: 24,
        bankBranchCode: "0  4n 4n",
        accountNum: "0  12   0"
    },
    "ccBE": {
        countryCode: "BE",
        countryName: "Belgi\u00EB",
        length: 16,
        bankBranchCode: "0  3n 0",
        accountNum: "0  7n   2n"
    },
    "ccBA": {
        countryCode: "BA",
        countryName: "Bosni\u00EB-Herzegovina",
        length: 20,
        bankBranchCode: "0  3n 3n",
        accountNum: "0   8n  2n"
    }
};

The lookup:

查找:

var countryCode = "AD";                          // <= Example for Andorra
var countryInfo = IBANInfo["cc" + countryCode];  // <= Note we add the prefix on lookup
alert("Country name: " + countryInfo.countryName); // <= Alerts "Country name: Andorra"

Looping through the keys in the map

循环遍历地图中的键

If you need (for any reason) to loop through all of these, since it's not an array you can't use a numeric index. Fortunately, this is exactly what the JavaScript for..inloop is for: It looks through the names (keys) of the object's properties:

如果您需要(出于任何原因)遍历所有这些,因为它不是数组,您不能使用数字索引。幸运的是,这正是 JavaScriptfor..in循环的用途:它查看对象属性的名称(键):

var key;
for (key in IBANInfo) {
    if (IBANInfo.hasOwnProperty(key)) {
        // ...use key here, it'll be "ccAD" for Andorra, etc...
    }
 }

(You use hasOwnPropertyto differentiate between properties the object has set on it directlyvs. those it gets from its prototype. If you're not familiar with JavaScript's prototypical inheritance, don't worry too much, just be sure to use a loop like the above.)

(你hasOwnProperty用来区分对象直接设置的属性和从它的原型中获取的属性。如果你不熟悉 JavaScript 的原型继承,不要太担心,一定要使用像这样的循环以上。)

Best of both worlds

两全其美

Since JavaScript arrays are objects, and all JavaScript objects are maps, you can even combine numeric indexing and indexing by country code. Here's an example of that:

由于 JavaScript 数组是对象,并且所有 JavaScript 对象都是映射,因此您甚至可以将数字索引和按国家/地区代码索引结合起来。这是一个例子:

The map:

地图:

// First, build the array
var IBANInfo = [
    {
        countryCode: "AD",
        countryName: "Andorra",
        length: 24,
        bankBranchCode: "0  4n 4n",
        accountNum: "0  12   0"
    },
    {
        countryCode: "BE",
        countryName: "Belgi\u00EB",
        length: 16,
        bankBranchCode: "0  3n 0",
        accountNum: "0  7n   2n"
    },
    {
        countryCode: "BA",
        countryName: "Bosni\u00EB-Herzegovina",
        length: 20,
        bankBranchCode: "0  3n 3n",
        accountNum: "0   8n  2n"
    }
];

// Now, cross-index it
var index, entry;
for (index = 0; index < IBANInfo.length; ++index)
{
    // Get the entry at this numeric index
    entry = IBANInfo[index];

    // Create the country code lookup for it
    IBANInfo["cc" + entry.countryCode] = entry;
}

This is where those prefixes become very important, because arrays have more properties than plain objects.

这就是这些前缀变得非常重要的地方,因为数组比普通对象具有更多的属性。

The lookup by country code is unchanged:

按国家/地区代码查找不变:

var countryCode = "AD";
var countryInfo = IBANInfo["cc" + countryCode];    // <= Country code lookup
alert("Country name: " + countryInfo.countryName); // <= Alerts "Country name: Andorra"

But now if (for some reason) you need to use a numeric index, you can also do that:

但是现在如果(出于某种原因)您需要使用数字索引,您也可以这样做:

var countryInfo = IBANInfo[0];                      // <= Numeric lookup
alert("Country name: " + countryInfo.countryName); // <= Also alerts "Country name: Andorra"

Cross-indexing after the fact as aboev is best only for static things like your IBAN map. If you were going to be adding or removing entries from this as part of your program, I'd probably make a reusable object out of it instead.

事后交叉索引作为 aboev 最好只适用于静态事物,例如您的 IBAN 地图。如果你打算在你的程序中添加或删除条目,我可能会用它来制作一个可重用的对象。

If I need things both numerically and by a key, I usually separate things out a bit by making the map aspects a property of the array rather than using the array directly. That requires only a small change to our loop that creates the map after we've initialized the array:

如果我需要数字和键的东西,我通常通过使地图方面成为数组的属性而不是直接使用数组来将事物分开。在我们初始化数组后,只需要对创建映射的循环进行小的更改:

The map:

地图:

// First, build the array
var IBANInfo = [
    /* ...same as before, omitted for space... */
];

// Now, cross-index it
var index, entry;
IBANInfo.byCC = {}; // A new plain object to be our map
for (index = 0; index < IBANInfo.length; ++index)
{
    // Get the entry at this numeric index
    entry = IBANInfo[index];

    // Create the country code lookup for it
    IBANInfo.byCC["cc" + entry.countryCode] = entry;
}

Country code lookups then use the byCCproperty:

国家/地区代码查找然后使用该byCC属性:

var countryCode = "AD";
var countryInfo = IBANInfo.byCC["cc" + countryCode]; // <= Country code lookup
   // The change is here:-^^^^^
alert("Country name: " + countryInfo.countryName);  // <= Alerts "Country name: Andorra"

So there you are, a bunch of options:

所以你有很多选择:

  • An array (look up by numeric index, not by country code; this is covered by other answers, or just leave the cross-indexing loop off the above)
  • A map (look up by country code, not by numeric index)
  • An array with additional properties (look up via numeric index orcountry code)
  • An array with a separate byCCproperty on it, just to keep us all sane
  • 一个数组(按数字索引查找,而不是按国家/地区代码查找;其他答案涵盖了这一点,或者只是将交叉索引循环放在上面)
  • 地图(按国家代码查找,而不是按数字索引查找)
  • 具有附加属性的数组(通过数字索引国家/地区代码查找)
  • 一个带有单独byCC属性的数组,只是为了让我们保持理智

Happy coding.

快乐编码。

回答by GorillaApe

You can use javascript like objects...

你可以像对象一样使用javascript...

For easyness you can use JSON (plain javascript)

为简单起见,您可以使用 JSON(纯 javascript)

var ibans={countries:[
{"name": "Andorra",
"countryCode" : "ad",
mplahmpla:mplah},
{"name": "Belgi?",
"countryCode" : "ad",
mplahmpla:mplah},
{"name": "Other",
"countryCode" : "ad",
mplahmpla:mplah}
]
}

then ibans.countries is an array with all countries... ibans.countries[1].name will be Belgie etc...

那么 ibans.countries 是一个包含所有国家的数组... ibans.countries[1].name 将是比利时等...

回答by TK.

You could use an array with associative arrays.

您可以将数组与关联数组一起使用。

var variable = {
    "countries" : [
                    {"countryname" : "Andorra",
                     "country code" : "AD",
                     "valid IBAN length" : "24",
                     "Bank/Branch Code (check1, bank, branch)": "0  4n 4n",
                     "Acount Number (check2, number, check 3)": "0  12  0"
                    }, 
                    {"countryname" : "Belgi?",
                     "country code" : "BE",
                     "valid IBAN length" : "16",
                     "Bank/Branch Code (check1, bank, branch)": "0  3n 0 ",
                     "Acount Number (check2, number, check 3)": "0   7n  2n"    
                    }
                  ]
    };

You might want to check out JSON format http://www.json.org/.

您可能想查看 JSON 格式http://www.json.org/

For example, variable(countries[0]["countryname"]);prints out "Andorra".

例如, variable(countries[0]["countryname"]);打印出“Andorra”。