[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条回答
Animai°情兽
2楼-- · 2019-01-21 07:42

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

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-21 07:47

Try using an Object, not an Array:

var test = new Object(); test[2300] = 'Some string';
查看更多
倾城 Initia
4楼-- · 2019-01-21 07:48

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.

查看更多
家丑人穷心不美
5楼-- · 2019-01-21 07:53

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);
查看更多
啃猪蹄的小仙女
6楼-- · 2019-01-21 08:02

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'
查看更多
甜甜的少女心
7楼-- · 2019-01-21 08:03

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)
查看更多
登录 后发表回答