developer tip

자바 스크립트 : 연관 배열에서 정수를 키로 사용합니까?

optionbox 2020. 9. 9. 07:55
반응형

자바 스크립트 : 연관 배열에서 정수를 키로 사용합니까?


새 자바 스크립트 배열을 만들고 정수를 키로 사용하면 해당 배열의 각 요소가 정의되지 않은 것으로 생성됩니다. 예를 들면 :

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

정의되지 않은 2298 개와 '일부 문자열'하나를 출력합니다.

정수 대신 2300을 문자열로 사용하도록 자바 스크립트를 얻으려면 어떻게해야합니까? 또는 2299 빈 인덱스를 인스턴스화하지 않도록 어떻게해야합니까?


사람들이 말하는 것처럼 물건을 사용하십시오. 그러나 정수 키는 가질 없습니다 . JavaScript는 정수를 문자열로 변환합니다 . 다음은 정의되지 않은 20을 출력합니다.

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

객체를 사용할 수 있습니다.

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

사람들이 말했듯이 javascript는 숫자 문자열을 정수로 변환하므로 연관 배열에서 직접 사용할 수는 없지만 객체는 비슷한 방식으로 작동합니다.

다음과 같이 개체를 만들 수 있습니다.

var object = {};

배열이 작동하면 값을 추가하십시오.

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

이것은 당신에게 줄 것입니다 :

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

그 후에 다른 언어로 된 배열처럼 액세스하여 키를 얻을 수 있습니다.

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

도움이 되었기를 바랍니다. 나는 테스트하고 작동합니다.


유스 케이스가 콜렉션에 데이터를 저장하는 경우 ES6Map유형을 제공합니다 .

초기화하는 것이 더 무겁습니다.

다음은 예입니다.

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 = {};

숫자를 새 속성의 키로 사용하면 숫자가 문자열로 바뀝니다.

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'

지도

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'

Try using an Object, not an 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);

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.


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.


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

참고URL : https://stackoverflow.com/questions/2002923/javascript-using-integer-as-key-in-associative-array

반응형