JavaScript ---- 字典学习

字典是一种以键-值对形式存储数据的数据结构

JavaScript的object类就是以字典的形式设计的,

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()  也可以定义

猜你喜欢

转载自blog.csdn.net/wanghongpu9305/article/details/110313615