Using an integer as a key in an associative array in JavaScript

后端 未结 10 2108
离开以前
离开以前 2020-12-07 15:34

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:

v         


        
10条回答
  •  自闭症患者
    2020-12-07 15:49

    If the use case is storing data in a collection then ECMAScript 6 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)
    

提交回复
热议问题