[removed] Using integer as key in associative arra

2019-01-21 07:04发布

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 instanciating 2299 empty indices?

10条回答
萌系小妹纸
2楼-- · 2019-01-21 08:05

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"]);
查看更多
贪生不怕死
3楼-- · 2019-01-21 08:06

You can just use an object:

var test = {}
test[2300] = 'Some string';
查看更多
We Are One
4楼-- · 2019-01-21 08:06

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.

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.

查看更多
唯我独甜
5楼-- · 2019-01-21 08:06

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.

查看更多
登录 后发表回答