<script> //创建字典 function Dictionary(){ var items = {}; this.set = function(key,value){ //向字典添加一个新的项 items[key] = value; } this.remove = function(key){ //从字典移除一个值 if(this.has(key)){ delete items[key]; return true; } return false; } this.has = function(key){ //判断值是否在字典中,返回布尔值 return key in items; } this.get = function(key){ //通过键值查找特定的数值并返回 return this.has(key) ? items[key] : undefined; } this.clear = function(){ //清空字典 items = {}; } this.size = function(){ //返回字典的元素数量 return Object.keys(items).length; } this.keys = function(){ //返回字典的键值名 return Object.keys(items); } this.values = function(){ //返回一个包含字典中所有值的数组 var values = []; for(var key in items){ if(this.has(key)){ values.push(items[key]) } } return values; } this.getItems = function(){ //返回items return items; } } var dictionary = new Dictionary(); dictionary.set(‘Gandalf‘, ‘gandalf@email.com‘); dictionary.set(‘John‘, ‘johnsnow@email.com‘); dictionary.set(‘Tyrion‘, ‘tyrion@email.com‘); console.log(dictionary.getItems()); </script>
原文地址:https://www.cnblogs.com/huangmin1992/p/10415337.html
时间: 2024-10-09 22:51:24