简体   繁体   English

使用 integer 作为关联数组中的键 JavaScript

[英]Using an integer as a key in an associative array in JavaScript

When I create a new JavaScript array, and use an integer as a key, each element of that array up to the integer is created as undefined.当我创建一个新的 JavaScript 数组并使用 integer 作为键时,该数组中直到 integer 的每个元素都被创建为未定义。

For example:例如:

var test = new Array();
test[2300] = 'Some string';
console.log(test);

will output 2298 undefined's and one 'Some string'.将 output 2298 未定义的和一个“一些字符串”。

How should I get JavaScript to use 2300 as a string instead of an integer, or how should I keep it from instantiating 2299 empty indices?我应该如何让 JavaScript 将 2300 用作字符串而不是 integer,或者我应该如何防止它实例化 2299 个空索引?

Use an object, as people are saying.正如人们所说,使用一个对象。 However, note that you can not have integer keys.但是,请注意您不能拥有整数键。 JavaScript will convert the integer to a string . JavaScript 会将整数转换为字符串 The following outputs 20, not undefined:以下输出 20,非未定义:

 var test = {} test[2300] = 20; console.log(test["2300"]);

You can just use an object:你可以只使用一个对象:

var test = {}
test[2300] = 'Some string';

As people say, JavaScript will convert a string of number to integer, so it is not possible to use directly on an associative array, but objects will work for you in similar way I think.正如人们所说,JavaScript 会将数字字符串转换为整数,因此无法直接在关联数组上使用,但我认为对象会以类似的方式为您工作。

You can create your object:您可以创建您的对象:

var object = {};

And add the values as array works:并在数组工作时添加值:

object[1] = value;
object[2] = value;

This will give you:这会给你:

{
  '1': value,
  '2': value
}

After that you can access it like an array in other languages getting the key:之后,您可以像其他语言中的数组一样访问它以获取密钥:

for(key in object)
{
   value = object[key] ;
}

I have tested and works.我已经测试和工作。

If the use case is storing data in a collection then ECMAScript 6 provides the Map type.如果用例将数据存储在集合中,则ECMAScript 6提供Map类型。

It's only heavier to initialize.只是初始化比较重。

Here is an example:下面是一个例子:

const map = new Map();
map.set(1, "One");
map.set(2, "Two");
map.set(3, "Three");

console.log("=== With Map ===");

for (const [key, value] of map) {
    console.log(`${key}: ${value} (${typeof(key)})`);
}

console.log("=== With Object ===");

const fakeMap = {
    1: "One",
    2: "Two",
    3: "Three"
};

for (const key in fakeMap) {
    console.log(`${key}: ${fakeMap[key]} (${typeof(key)})`);
}

Result:结果:

=== With Map ===
1: One (number)
2: Two (number)
3: Three (number)
=== With Object ===
1: One (string)
2: Two (string)
3: Three (string)

Compiling other answers:编译其他答案:

Object对象

var test = {};

When using a number as a new property's key, the number turns into a string:当使用数字作为新属性的键时,数字会变成字符串:

test[2300] = 'Some string';
console.log(test['2300']);
// Output: 'Some string'

When accessing the property's value using the same number, the number is turned into a string again:当使用相同的数字访问属性的值时,数字再次变成字符串:

console.log(test[2300]);
// Output: 'Some string'

When getting the keys from the object, though, they aren't going to be turned back into numbers:但是,当从对象中获取键时,它们不会被转换回数字:

for (var key in test) {
    console.log(typeof key);
}
// Output: 'string'

Map地图

ECMAScript 6 allows the use of the Map object ( documentation , a comparison with Object ). ECMAScript 6 允许使用 Map 对象( 文档与 Object 的比较)。 If your code is meant to be interpreted locally or the ECMAScript 6 compatibility table looks green enough for your purposes, consider using a Map:如果您的代码打算在本地进行解释,或者ECMAScript 6 兼容性表看起来足以满足您的目的,请考虑使用 Map:

var test = new Map();
test.set(2300, 'Some string');
console.log(test.get(2300));
// Output: 'Some string'

No type conversion is performed, for better and for worse:不执行类型转换,无论好坏:

console.log(test.get('2300'));
// Output: undefined
test.set('2300', 'Very different string');
console.log(test.get(2300));
// Output: 'Some string'

Use an object instead of an array.使用对象而不是数组。 Arrays in JavaScript are not associative arrays. JavaScript 中的数组不是关联数组。 They are objects with magic associated with any properties whose names look like integers.它们是具有魔法的对象,与名称看起来像整数的任何属性相关联。 That magic is not what you want if you're not using them as a traditional array-like structure.如果您不将它们用作传统的类似数组的结构,那么这种魔法就不是您想要的。

var test = {};
test[2300] = 'some string';
console.log(test);

尝试使用对象,而不是数组:

var test = new Object(); test[2300] = 'Some string';

Get the value for an associative array property when the property name is an integer:当属性名称为整数时,获取关联数组属性的值:

Starting with an associative array where the property names are integers:从属性名称为整数的关联数组开始:

var categories = [
    {"1": "Category 1"},
    {"2": "Category 2"},
    {"3": "Category 3"},
    {"4": "Category 4"}
];

Push items to the array:将项目推送到数组:

categories.push({"2300": "Category 2300"});
categories.push({"2301": "Category 2301"});

Loop through the array and do something with the property value.循环遍历数组并使用属性值执行某些操作。

for (var i = 0; i < categories.length; i++) {
    for (var categoryid in categories[i]) {
        var category = categories[i][categoryid];
        // Log progress to the console
        console.log(categoryid + ": " + category);
        //  ... do something
    }
}

Console output should look like this:控制台输出应如下所示:

1: Category 1
2: Category 2
3: Category 3
4: Category 4
2300: Category 2300
2301: Category 2301

As you can see, you can get around the associative array limitation and have a property name be an integer.如您所见,您可以绕过关联数组的限制,并将属性名称设为整数。

NOTE: The associative array in my example is the JSON content you would have if you serialized a Dictionary<string, string>[] object.注意:我的示例中的关联数组是序列化 Dictionary<string, string>[] 对象时将拥有的 JSON 内容。

Simple solution if you would rather use an array.如果您更愿意使用数组,则可以使用简单的解决方案。 When adding the number just preface it with a letter.添加数字时,只需在其前面加上一个字母。

eg例如

let ctr = 3800;
let myArray=[];
myArray["x" + ctr.toString()]="something";
myArray["x" + (ctr+1).toString()]="another thing";

Then just add the "x" in access routines that call the number as an index.然后只需在调用数字作为索引的访问例程中添加“x”。 eg: console.log( myArray["x3800"] );例如: console.log( myArray["x3800"] ); or: console.log( myArray["x"+ numberOfYourChoice.toString()] );或者: console.log( myArray["x"+ numberOfYourChoice.toString()] );

使用对象 - 以整数作为键 - 而不是数组。

Sometimes I use a prefixes for my keys.有时我为我的键使用前缀。 For example:例如:

var pre = 'foo',
    key = pre + 1234

obj = {};

obj[key] = val;

Now you don't have any problem accessing them.现在您访问它们没有任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM