Javascript:使用整数作为关联数组中的键?

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

Javascript: Using integer as key in associative array?

javascriptassociative-array

提问by Claudiu

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. for example:

当我创建一个新的 javascript 数组,并使用一个整数作为键时,该数组中直到整数的每个元素都被创建为未定义。例如:

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

will output 2298 undefined's and one 'Some string'.

将输出 2298 个未定义的和一个 'Some string'。

How should I get javascript to use 2300 as a string instead of an integer, or how should I keep it from instanciating 2299 empty indices?

我应该如何让 javascript 使用 2300 作为字符串而不是整数,或者我应该如何防止它实例化 2299 个空索引?

回答by Claudiu

Use an object, as people are saying. However, note that you can nothave integer keys. JavaScript will convert the integer to a string. The following outputs 20, not undefined:

正如人们所说,使用一个对象。但是,请注意您不能拥有整数键。JavaScript 会将整数转换为字符串。以下输出 20,非未定义:

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

回答by Annie

You can just use an object:

你可以只使用一个对象:

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

回答by Jesuslg123

As people say javascript will convert an string of number to integer so 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 array in other languages getting the key:

之后,您可以像其他语言中的数组一样访问它以获取密钥:

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

I hope this is useful! I have tested and works.

我希望这是有用的!我已经测试和工作。

回答by Pragmateek

If the use-case is storing data in a collection then ES6provides the Maptype.

如果用例将数据存储在集合中,则ES6提供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)

回答by wordbug

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

地图

ES6 allows the use of the Map object (documentation, a comparison with Object). If your code is meant to be interpreted locally or the ES6 compatibility tablelooks green enough for your purposes, consider using a Map:

ES6 允许使用 Map 对象(文档与 Object 的比较)。如果您的代码打算在本地进行解释,或者ES6 兼容性表看起来足以满足您的目的,请考虑使用 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'

回答by Jeff Hammerbacher

Try using an Object, not an Array:

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

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

回答by bdukes

Use an object instead of an array. Arrays in JavaScript are not associative arrays. 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.

使用对象而不是数组。JavaScript 中的数组不是关联数组。它们是具有魔法的对象,与名称看起来像整数的任何属性相关联。如果您不将它们用作传统的类似数组的结构,那么这种魔法就不是您想要的。

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

回答by Jason Williams

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 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 you would have if you serialized a Dictionary<string, string>[] object.

注意:我的示例中的关联数组是序列化 Dictionary<string, string>[] 对象时将拥有的 json。

回答by pictus

Sometimes i use a prefixes for my keys. For example:

有时我为我的键使用前缀。例如:

var pre = 'foo',
       key = pre + 1234
       obj = {};

obj[ key ] = val;

Now you have no Problem accessing them.

现在您可以毫无问题地访问它们。

回答by Upperstage

Use an object - with an integer as the key - rather than an array.

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