【问题标题】:How do you get the key at specifc index in javascript map object?您如何获取 javascript 映射对象中特定索引处的键?
【发布时间】:2016-10-15 18:48:47
【问题描述】:

假设我有以下地图对象

const items = new Map([['item1','A'], ['item2','B'], ['item3', 'C']])

我想获取索引 2 处的键。除了使用 for 循环来获取索引 = 2 处的项的键之外,还有其他方法吗?

按照答案解决了这个问题-

Array.from(items.keys())[2]

【问题讨论】:

标签: javascript ecmascript-6


【解决方案1】:

const a = new Map([['1 Item', 'abc'], ['2 Item', 'def']]);
let indexVal =   [...a][1];
console.log(indexVal);

【讨论】:

    【解决方案2】:

    这是一个更全面的解决方案,它不会毫无意义地将所有值复制到一个数组中:

    function get_nth_key<K, V>(m: Map<K, V>, n: number): K | undefined {
      if (n < 0) {
        return undefined;
      }
      const it = m.keys();
      for (;;) {
        const res = it.next();
        if (res.done) {
          return undefined;
        }
        if (n <= 0) {
          return res.value;
        }
        --n;
      }
    }
    
    const m = new Map<string, string>([['item1', 'A'], ['item2', 'B'], ['item3', 'C']]);
    
    console.log(get_nth_key(m, -1));
    console.log(get_nth_key(m, 0));
    console.log(get_nth_key(m, 1));
    console.log(get_nth_key(m, 2));
    console.log(get_nth_key(m, 3));
    

    输出:

    undefined
    item1
    item2
    item3
    undefined
    

    【讨论】:

      【解决方案3】:

      要获取索引 2 处的键,请执行以下操作:

      // Your map
      var items = new Map([['item1','A'], ['item2','B'], ['item3', 'C']]);
      
      // The key at index 2
      var key = Array.from(items.keys())[2];                 // Returns 'item3'
      
      // The value of the item at index 2
      var val1 = items.get(key);                             // Returns 'C'
      
      
      // ... or ...
      var val2 = items.get(Array.from(items.keys())[2]);     // Returns 'C'
      

      【讨论】:

        【解决方案4】:

        地图可能是有序的,但它们没有被索引。获取第 n 个项目的唯一方法是循环。

        【讨论】:

        • 真可惜...这里的任何 TC39 人都想权衡一下为什么他们没有被索引?
        • @geoyws 因为那不是他们的目的?如果您想要索引集合,请使用数组。
        • 我正在寻找一种解决方案,它允许我拥有一组有序和索引的键和值...数组不能做键和值,需要循环查找某个“钥匙”。对象没有排序并且变得混乱。地图没有索引,需要循环来获取索引。很遗憾,因为我认为地图会解决我的问题。
        • @geoyws 你可以在两个 Maps + 一个数组之上构建你想要的东西。一个 Map 存储键值对,一个 Map 存储键索引映射,一个数组存储索引键映射。根据相关结构的信息,使每个操作(按键设置、按键删除、按键查找、索引查找)对所有这三个结构都执行正确的操作。这不需要语言支持。
        • @geoyws ES6 可能会指定一个顺序(用于特定操作,但例如不用于循环)以保持引擎之间的行为一致,但这并不意味着对象旨在用作有序集合。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多