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.

For example:

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

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

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?

121810 次浏览

你可以只使用一个对象:

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

尝试使用 Object,而不是 Array:

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

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.

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

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

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

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

正如人们所说,JavaScript 会把一串数字转换成整数,所以不可能直接在关联数组上使用,但我认为对象也会以类似的方式为你工作。

您可以创建您的对象:

var object = {};

And add the values as array works:

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

这会给你:

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

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

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

I have tested and works.

当属性名为整数时,获取关联数组属性的值:

Starting with an 关联数组 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"});

循环遍历数组并对属性值执行某些操作。

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
}
}

控制台输出应该是这样的:

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

正如你所看到的,你可以绕过关联数组限制,将属性名称设置为整数。

注意: 我的示例中的关联数组是如果序列化 Dictionary < string,string > []对象,那么您将拥有的 JSON 内容。

有时我用前缀作为我的键,例如:

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


obj = {};


obj[key] = val;

现在访问它们没有任何问题了。

如果用例在集合中存储数据,则 ECMAScript 6提供 Map类型。

初始化只会更重。

这里有一个例子:

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)})`);
}

结果:

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

编译其他答案:

反对

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'

当使用相同的数字访问属性值时,该数字再次转换为字符串:

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

不过,当从物体上获取钥匙时,它们不会被转换回数字:

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

地图

ECMAScript 6允许使用 Map 对象(文件与对象的比较)。如果您的代码需要在本地进行解释,或者 ECMAScript 6兼容性表看起来足够绿,那么可以考虑使用 Map:

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

无论是好是坏,都不执行类型转换:

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

如果您更愿意使用数组,那么这是一个简单的解决方案。 加数字的时候只要在前面加一个字母就行了。

e.g.

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

然后在访问例程中添加“ x”,这些例程调用该数字作为索引。 例如: console.log( myArray["x3800"] ); or: console.log( myArray["x"+ numberOfYourChoice.toString()] );