- Hands-On Data Structures and Algorithms with JavaScript
- Kashyap Mukkamala
- 256字
- 2021-06-30 19:12:16
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 map, it 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
- Docker技術(shù)入門與實(shí)戰(zhàn)(第3版)
- 控糖控脂健康餐
- Rust編程從入門到實(shí)戰(zhàn)
- FFmpeg入門詳解:音視頻流媒體播放器原理及應(yīng)用
- 神經(jīng)網(wǎng)絡(luò)編程實(shí)戰(zhàn):Java語言實(shí)現(xiàn)(原書第2版)
- Apache Spark 2 for Beginners
- SAS數(shù)據(jù)統(tǒng)計(jì)分析與編程實(shí)踐
- C#程序設(shè)計(jì)基礎(chǔ):教程、實(shí)驗(yàn)、習(xí)題
- Julia高性能科學(xué)計(jì)算(第2版)
- WordPress 4.0 Site Blueprints(Second Edition)
- Instant PHP Web Scraping
- ArcGIS for Desktop Cookbook
- Node.js 12實(shí)戰(zhàn)
- Illustrator CS6設(shè)計(jì)與應(yīng)用任務(wù)教程
- Java EE 7 with GlassFish 4 Application Server