最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Best way to create a hashmap in ES6 with number as index - Stack Overflow

programmeradmin8浏览0评论

I want to build an hashmap class, or use one that es with the language.

The index are integers. If I try to do this with an array, I see on the debugger than the size of the array is equals to the higher integer key.

Ie, if my hashmap has two elements, Map[0]= 'word1' and Map[1023]= 'word2' I can see that the array has size 1024. I'd prefer not to waste so much space.

I can't make any assumption on how the keys are distributed.

I want to build an hashmap class, or use one that es with the language.

The index are integers. If I try to do this with an array, I see on the debugger than the size of the array is equals to the higher integer key.

Ie, if my hashmap has two elements, Map[0]= 'word1' and Map[1023]= 'word2' I can see that the array has size 1024. I'd prefer not to waste so much space.

I can't make any assumption on how the keys are distributed.

Share Improve this question edited Apr 28, 2017 at 19:43 John Culviner 23k6 gold badges58 silver badges53 bronze badges asked Dec 24, 2015 at 1:17 SnickSnick 1,04212 silver badges29 bronze badges 5
  • 2 var blah = {} (don't use var Map ... Map is a thing in browsers except early internet exploders < 11) – Jaromanda X Commented Dec 24, 2015 at 1:21
  • No, the size is still 1023. – Snick Commented Dec 24, 2015 at 1:34
  • You're doing it wrong. A js object doesn't have a length – Jaromanda X Commented Dec 24, 2015 at 1:35
  • "I'd prefer not to waste so much space." Arrays in JavaScript work differently than in other languages. They are basically just objects. An array that has length 1000 doesn't necessarily take up that much space. – Felix Kling Commented Dec 24, 2015 at 8:47
  • Correct, but you are not taking advantage of new ES6 browser implementations. An array is probably implemented with a linked list and a hashmap, but we don't have control on the pre allocated size. – Snick Commented Dec 26, 2015 at 19:08
Add a ment  | 

1 Answer 1

Reset to default 21

ECMAScript 6 introduces a true Map type which can be used as follows:

const m = new Map();
m.set(0, "word1");
m.set(1023, "word2");
for(const [key, value] of m) {
    console.log(key, value, typeof key);
}

Note how key is still a number - using an object literal, keys are always strings. It also provides a size property for counting key/value pairs:

const m = new Map();
m.set(0, "word1");
m.set(1023, "word2");
console.log(m.size); // 2

Babel REPL Example

发布评论

评论列表(0)

  1. 暂无评论