Javascript:在关联数组中使用整数作为键? [英] Javascript: Using integer as key in associative array?
问题描述
当我创建一个新的javascript数组,并使用整数作为键时,该数组中每个直到整数的元素都被创建为undefined。
例如:
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);
将输出2298个undefined's和一个'Some string'。
will output 2298 undefined's and one 'Some string'.
我应该如何让javascript使用2300作为字符串而不是整数,或者我应该如何保持它不会实现2299空索引?
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将将整数转换为字符串。以下输出20,未定义:
Use an object, as people are saying. However, note that you can not have integer keys. JavaScript will convert the integer to a string. The following outputs 20, not undefined:
var test = {}
test[2300] = 20;
console.log(test["2300"]);
这篇关于Javascript:在关联数组中使用整数作为键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!