js常用数据结构

列表

   列表是一个序列,用中括号[]表示,用逗号‘,’分隔, 
   列表的每个元素的类型可以是对象,数字,字符串,列表,布尔值等
   三大特性: 有序性,异构性,本地可修改
   var list = [1, "a", true, {b: "c"}];
   

队列

线性结构,先进先出,
  就像银行排队办业务, 先排队的先办业务,办完就离开,后来的人插到最后排队 

function Queue(){
    this.dataStore = []; // 利用数组实现队列
    this.enQueue = enQueue; // 入队
    this.deQueue = deQueue; // 出队
    this.front = front; // 取队首元素
    this.end = end; // 取队尾元素
    this.showAll = showAll; // 显示队列内的所有元素
    this.clear= clear; // 清空队列
}

function enQueue(element){
    this.dataStore.push(element);
}

function deQueue(){
    this.dataStore.shift();
}

function front(){
    return this.dataStore[0];
}

function end(){
    return this.dataStore[this.dataStore.length-1];
}

function showAll(){
    return this.dataStore.toString();
}

function clear(){
    this.dataStore. = [];
}

   

线性结构,先进后出
  就像出入电梯一样,先进去的人在里面,后进去的人往电梯口靠,出来的时候是从后进去的人开始

function Stack(){
    this.dataStore = []; //数据结构为数组
    this.top = 0;  // 指向栈顶元素
    this.push = push; // 向栈顶添加一个元素
    this.pop = pop; // 删除栈顶元素
    this.peek = peek; // 返回栈顶元素
    this.length = length;  // 返回栈的长度
    this.clear = clear; // 清空栈
}

function push(item){
    this.dataStroe[++this.top] = item;
}

function pop(){
    this.dataStore[--this.top];
}

function peek(){
    return this.dataStore[this.top];
}

function length(){
    return this.top;
}

function clear(){
    delete this.dataStore;
    this.dataStore = 0;
    this.top = 0;
}

字典

     是以键值对的方式存储数据
    js的Object类就用字典的设计的
    字典类的基础就是Array类

function dictionary(){
    this.dataStore= []; 
    this.add = add;  // 添加一个键值对
    this.remove = remove; // 删除一个键值对
    this.showAll = showAll;  // 查看字典所有键值对
    this.count = count; // 返回字典元素数量
    this.clear = clear; // 清空字典
}

function add(key, value){
    this.dataStore[key] = value;
}

function remove(key){
    if( this.dataStore[key] ) delete this.dataStore[key];
    else  return "not found";
}

function find(key){
    return this.dataStore[key];
}

function showAll () {
    return JSON.stringify(this.dataStore);
}

function count(){
    var n = 0;
    for(var key in this.dataStore){
        n++;
    }
    return n;
}

function clear(){
    for(var key in this.dataStore){
        delete this.dataStore[key];
    }
}

 

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值