繁体   English   中英

你如何在javascript映射对象中获取特定索引处的键?

[英]How do you get the key at specifc index in javascript map object?

假设我有以下地图对象

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

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

根据答案得到这个工作 -

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

要获取索引 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'

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM