可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
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"]);
回答2:
You can just use an object:
var test = {}
test[2300] = 'Some string';
回答3:
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.
回答4:
If the use-case is storing data in a collection then ES6 provides the Map
type.
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)
回答5:
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 table looks green enough for your purposes, consider using a 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'
回答6:
Try using an Object, not an Array:
var test = new Object(); test[2300] = 'Some string';
回答7:
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);
回答8:
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.
回答9:
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.
回答10:
Use an object - with an integer as the key - rather than an array.