zoukankan      html  css  js  c++  java
  • Javacript实现字典结构

    字典是一种用[键,值]形式存储元素的数据结构。也称作映射,ECMAScript6中,原生用Map实现了字典结构。
    下面代码是尝试用JS的Object对象来模拟实现一个字典结构。

    <script>
    //set添加 get获取 has是否有 remove删除 values获取所有value size获取长度 clear清除所有
    function Dict(){
    	this.item = {};
    }
    
    //是否存在元素
    Dict.prototype.has = function(key){
    	return key in this.item;
    }
    
    //set添加元素
    Dict.prototype.set = function(key,value){
    	if(!this.has(key)){
    		this.item[key] = value;
    		return true;
    	}
    	return false;
    }
    
    //查找并返回元素
    Dict.prototype.get = function(key){
    	return this.has(key) ? this.item[key] : undefined;
    }
    
    //移除元素
    Dict.prototype.remove = function(key){
    	if(this.has(key)){
    		delete this.item[key];
    		return true;
    	}
    	return false;
    }
    
    //返回字典所包含元素的数量
    Dict.prototype.size = function(key){
    	var length = 0;
    	for(var i in this.item){
    		length++;
    	}
    	return length;
    }
    
    //清空字典所有元素
    Dict.prototype.clear = function(){
    	if(this.size() > 0){
    		this.item = {};
    		return true;
    	}
    	return false;
    }
    
    //把字典所有元素用数组的形式返回
    Dict.prototype.values = function(){
    	var values = []
    	if(this.size() > 0){
    		for(var i in this.item){
    			values.push(i);
    		}
    		return values;
    	}
    }
    
    var dict = new Dict();
    dict.set('a',1);
    dict.set('b',2);
    dict.set('c',3);
    console.log(dict.values()); //["a", "b", "c"]
    dict.remove('b');
    console.log(dict.size()); //2
    dict.clear();
    console.log(dict.size()); //0
    console.log(dict.clear()); //false
    </script>
    
  • 相关阅读:
    token验证流程
    mongodb常用命令
    vue生命周期详解
    json-server基本使用
    Vue实现一个简单的todolist
    [高级软件工程教学]个人第2次作业第一次测评结果
    [福大高级软工教学]个人第1次作业成绩公布
    nginx+tomcat负载均衡
    apache 工作模式
    Apache主要的配置文件们
  • 原文地址:https://www.cnblogs.com/jaychan/p/5973297.html
Copyright © 2011-2022 走看看