在字典中存儲(chǔ)的值是【鍵巴粪、值】對(duì)何址,字典和集合很相似斩熊,集合以【值琐簇、值】的形式存儲(chǔ)。字典也稱作映射座享。
字典的代碼實(shí)現(xiàn):
function Dictionary() {
? ? var items = {};
? ? this.set = function(key, value) {
? ? ? ? if(!this.has()) {
? ? ? ? ? ? items[key] = value;
? ? ? ? ? ? return true;
? ? ? ? }else {
? ? ? ? ? ? return false;
? ? ? ? }
? ? }
? ? this.remove = function(key) {
? ? ? ? if(this.has(key)) {
? ? ? ? ? ? delete items[key];
? ? ? ? ? ? return true;
? ? ? ? }else {
? ? ? ? ? ? return false;
? ? ? ? }
? ? }
? ? this.has = function(key) {
? ? ? ? return key in items;
? ? }
? ? this.get = function(key) {
? ? ? ? return this.has(key) ? items[key] : null;
? ? }
? ? this.clear = function() {
? ? ? ? items = [];
? ? }
? ? this.size = function() {
? ? ? ? return Object.keys().length;
? ? }
? ? this.keys = function() {
? ? ? ? return Object.keys();
? ? }
? ? this.values = function() {
? ? ? ? const? values = [];
? ? ? ? for(var k in items) {
? ? ? ? ? ? values.push(items[k]);
? ? ? ? }
? ? ? ? return values;
? ? }
}
var dic = new Dictionary();
dic.set('a', '一');
dic.set('b', '二');
dic.set('c', '三');
console.log(dic.values()); // [ '一', '二', '三' ]
dic.remove('b');
console.log(dic.values()); // [ '一', '三' ]
console.log(dic.get('c')); // 三