Map儲存一連串的鍵值對(kay-value pair),取值時透過特定的鍵(key)去取得特定的值(value),若用生活例子來比喻,則像小學班級的學生編號,1號是小明,2號是小健…等,點名時若點到1號,則小明同學就會喊”右!”,例子中的編號就像是鍵(key),相對應的學生則是值(value)
影片中提到的例子,透過月份名稱取得欲取得的值:
Javascript裡的陣列已實作Map物件,但仍可自己實作Stack
let map2 = new Map();
map2.has('hands');
map2.entries();
let keyObj = {},
keyFunc = function() {};
map2.set('hello', 'string value');
map2.set(keyObj, 'obj value');
map2.set(keyFunc, 'func value');
map2.set(NaN, 'NaN value')
console.log(map2.size);
console.log(map2.get('hello'));
console.log(map2.get(keyObj));
console.log(map2.get(keyFunc));
console.log(map2.get(NaN));
// 4
// "string value"
// "obj value"
// "func value"
// "NaN value"
var myMap = function() {
this.collection = {}; // Stack元素
this.count = 0; // Stack長度
}
...
this.size = function() {
return this.count;
};
...
...
this.set = function(key, value) {
this.collection[key] = value;
this.count++;
};
...
...
this.has = function(key) {
return (key in this.collection);
};
...
...
this.get = function(key) {
return (key in this.collection) ? this.collection[key] : null;
};
...
...
this.delete = function(key) {
if (key in this.collection) {
delete this.collection[key];
this.count--;
}
};
...
...
this.values = function() {
let result = new Array();
for (let key of Object.keys(this.collection)) {
result.push(this.collection[key]);
};
return (result.length > 0) ? result : null;
};
...
...
this.clear = function() {
this.collection = {};
this.count = 0;
};
...
let myMap = function() {
this.collection = {};
this.count = 0;
this.size = function() {
return this.count;
};
this.set = function(key, value) {
this.collection[key] = value;
this.count++;
};
this.has = function(key) {
return (key in this.collection);
};
this.get = function(key) {
return (key in this.collection) ? this.collection[key] : null;
};
this.delete = function(key) {
if (key in this.collection) {
delete this.collection[key];
this.count--;
}
};
this.values = function() {
let result = new Array();
for (let key of Object.keys(this.collection)) {
result.push(this.collection[key]);
};
return (result.length > 0) ? result : null;
};
this.clear = function() {
this.collection = {};
this.count = 0;
};
};
let map = new myMap();
map.set('arms', 2);
map.set('fingers', 10);
map.set('eyes', 2);
map.set('belley button', 1);
console.log(map.get('fingers'));
console.log(map.size());
console.log(map.values());
// 10
// 4
// [2, 10, 2, 1]