JavaScript ---- dictionary learning

A dictionary is a data structure that stores data in the form of key-value pairs

JavaScript's object class is designed in the form of a dictionary,

function Dictionary() {
			this.add = add;
			this.datastore = new Array();
			this.find = find;
			this.remove = remove
			this.showAll = showAll
			this.count = count
			this.clear = clear
		}

		function add(key, value) { // 添加
			this.datastore[key] = value
		}

		function find(key) { //  查找
			return this.datastore[key]
		}

		function remove(key) { // 删除
			delete this.datastore[key];
		}

		function showAll() { // 显示所有
			for (var key in Object.keys(this.datastore).sort()) {
				console.log(key + "-------" + this.datastore[key])
			}
		}

		function count() { // 字典中的元素个数
			var n = 0;
			for (var key in Object.keys(this.datastore)) {
				// console.log(key)
				++n;
			}
			return n;
		}
		function clear() { // 清空
			for(var key in Object.keys(this.datastore)){
				delete this.datastore[key]
			}
		}
		var pbook = new Dictionary();
		pbook.add("Raymond","123");
		pbook.add("David", "345");
		pbook.add("Cynthia", "456");
		pbook.add("Mike", "723");
		pbook.add("Jennifer", "987");
		pbook.add("Danny", "012");
		pbook.add("Jonathan", "666");
		pbook.showAll();
		
		console.log(pbook.datastore)

 new Map() can also be defined

Guess you like

Origin blog.csdn.net/wanghongpu9305/article/details/110313615