官术网_书友最值得收藏!

Exploring the origin of sets and maps

Before we try and understand how to use sets and maps in real-world applications, it is more meaningful to understand the origin of sets and maps and why we need them in JavaScript in the first place.

Traditional arrays, until ES5, did not support a few major features, that developers usually want to leverage:

  • Acknowledging that it contains a particular element
  • Adding new elements without having duplicates

This led to developers implementing their own versions of sets and maps, which were available in other programming languages. A common implementation of a set and map using JavaScript's Object is as follows:

// create an empty object
var setOrMap = Object.create(null);

// assign a key and value
setOrMap.someKey = someValue;

// if used as a set, check for existence
if(setOrMap.someKey) {
// set has someKey
}

// if used as a map, access value
var returnedValue = setOrMap.someKey;

Although a lot of prototype headaches can be avoided by using Object.create to create the set or mapit still does not resolve the fact that the main Key that is being held can only be a string because Object only allows keys as strings, so we could unintentionally end up with values overwriting each other:

// create a new map object
let map = Object.create(null);

// add properties to the new map object
let b = {};
let c = {};
map[b] = 10
map[c] = 20

// log map
Object [object Object]: 20
主站蜘蛛池模板: 吐鲁番市| 新乡县| 鞍山市| 通渭县| 渝中区| 璧山县| 怀化市| 龙口市| 松原市| 甘孜县| 自贡市| 濮阳县| 阜康市| 上饶市| 碌曲县| 青铜峡市| 雷波县| 高邑县| 澄迈县| 安阳县| 大埔区| 滕州市| 龙山县| 绥江县| 阳新县| 文山县| 河东区| 乳源| 青州市| 玉林市| 乃东县| 兴安盟| 民县| 华亭县| 康马县| 临夏县| 望谟县| 娱乐| 房山区| 嘉善县| 闻喜县|