JS数组和数据结构的理解

创建数组的方法有两种;

var  arr1 = new Array();        //也可以创建指定长度的数组,默认值都是undefined;
        arr1[0] = 'this is first ele';
        arr1[1] = 1;
        
var arr2 = ['this is first ele',12];

arr1.length   //输出数组多少个元素

有两种方法向数组里添加元素

var arr = [1,2,3,4,5,6];

//删除和增加元素在最前和最后位置
arr.push(7)          //->7输出数组元素的个数,在数组后面添加元素
arr.unshift(0)        //->8输出数组元素的个数,在数组前面添加元素

arr.pop()                 //->7  输出删除掉的元素,删除最后面的元素
arr.shift()                 //->0 输出删除掉的元素,删除最前面的元素

//增加或者删除指定位置的元素

arr.splice(arg1,arg2,arg3,...)        //arg1开始的位置(不包含),arg2要删除的个数,是0的话不删除,
//arg3及后面是要替换的元素

arr.splice(1,2,'first','second');         //->[2,3]输出删除的元素,同时替换元素

数组一些常用的方法

var  number = [1,2,3,4,5,6];
var str = ['a','b','c','d','e'];

//连接两个数组,返回新的数组  ->concat();
number.concat(str)            // [1, 2, 3, 4, 5, 6, "a", "b", "c", "d", "e"]

//和字符串类似的方法 ->slice(start,end),indexOf(),lastIndexOf()都是返回新的数组;

number.slice(1,3);                    //[2,3]如果参数是负数,则和长度加转为正数,但两个参数不会按照
//大小调换位置
number.indexOf(3);                //2
number.lastIndexOf(3);             //2

//数组转成字符串,toString(),join();注意是把整个数组转为一个新字符串,同时忽略所有的引号,
//null也会忽略,

str.toString() ===str.join();  //true "a,b,c,d,e"
join()        //参数不是空的话,就把参数取代数字的分隔符" , ";

//可以通过字符串方法split(',')重新生成数组;
var s = str.toString();
s.split(',') == str;    //true

ES5新的方法
1,Array.forEach(callback,[this.obj]),对数组的每个元素都执行函数

forEach

在CHROME中输出如上,函数默认有三个参数
1,数组元素
2,元素索引
3,整个数组

var names = ['Biden','Cheney','Gore'];
var presdent = {
    names : ['obama','bush','cliton'],
    read : function(name){if(this.names[0] == 'obama'){console.log(name);}},
    job : function(name){alert(name);}
}

presdent.names.forEach(presdent.read);        //undefined;
presdent.names.forEach(presdent.read,presdent);        //obama,bush,cliton

forEach(callback,[object])的第二个参数可以指定要执行的上下文,比如this的指向问题,还有个小问题,如果数组中已经删除的元素是不会在执行函数的,虽然在数组中显示undefined(注意这个值和
直接赋值的undefined是不一样的,类似于 “” 和undefined 的区别)

2,Array.every(callback,[this.obj])Array.some(callback,[this.obj])
返回 true / false;

var number = [2,4,5,6];
var newnum = 3;
function a(arg){
    if(arg>newnum){
        return true;
    }
}
function b1(arg){
    if(number.some(a)){
        console.log('All BIGGER');
    }else{
        console.log('there\' at least one small')
    }
}
//All BIGGER
function b2(arg){
    if(number.ervey(a)){
        console.log('All BIGGER');
    }else{
        console.log('there\' at least one small')
    }
}
//there' at least one small

从例子中我们可以知道,some方法如果有一个真就返回true,every方法全部真,才返回true;

3,Array.map(callback,[this.obj])Array.filter(callback,[this.obj]);
返回新的数组

var number = [1,3,5,7,8];

function a(arg){
    if(arg>4){
        return 'this number is >4: '+ arg;
    }{
        return 'this number is<4: '+arg ;
    }
}
number.map(a);    //返回执行后的结果数组,如果函数没有返回值则数组都是undefined;
//["this number is<4: 1", "this number is<4: 3", "this number is >4: 5", 
//"this number is >4: 7", "this number is >4: 8"];

number.filter(a) //返回执行函数后为true的原数组元素,如果函数返回值不是true/false则返回全部
//注意函数的返回值只要松散相等即可如: 0 == false;
// [1, 3, 5, 7, 8]

4,Array.reduce(callback[, initialValue])Array.reduceRight(callback[, initialValue])
返回callback的返回值;

//callback(pre,cur,index,array)有四个参数,其中index 和array和之前的一样,pre和cur代表
//前一个元素和当前的元素(pre后面一个元素);
//如果 initialValue没有省略,则pre =  initialValue,cur为数组第一个元素;
// initialValue省略的话,pre默认为数组第一个元素,cur为第二个
var arr  = [1,3,5,7,9];
function sum(pre,cur,index,array){var add = pre + cur;return add};
arr.reduce(sum,11)
//结果如下
initialValue = pre = 11;  cur = arr[0];
//第一次
add1= pre + arr[0]; cur = arr[1];
//第二次
add2 = add1 +arr[1]
//第 三次
add3 = add2 + arr[2];
//第四次
add4 = add3 + arr[3];
//最后一次
add5 = add4 + arr[4];
//36
arr.reduce(sum)    //25
add.reduceRight(sum)    //25
//和rudece一样区别是index从最后往前;

JS的数据结构

1. 栈 -—后进先出的有序集合;

function Stack(){
    var items = [];
    this.push = function(ele){ items.push(ele);};
    this.pop = function(ele){ return items.pop(ele);};
    this.isEmpty = function(){ return items.length == 0;};
    this.size = function(){return items.length;};
    this.clear = function(){itmes = [];};
    this.show = function(){console.log( items.toString())};
}
//转化进制
function to2(number){
    var tem = new Stack();
    var rem;
    var distNumber = "";
    while(number > 0){
        rem = number%2;
        tem.push(rem);
        number = Math.floor(number/2);
    }
    while(!tem.isEmpty()){
        distNumber += tem.pop().toString();
    }
    return distNumber;
}

2,队列 ——先进先出的有序集合(区分堆栈)

function Queue(){
    var items = [];
    this.front = function(ele){ items.unshift(ele);};
    this.first = function(){return items[0];};
    this.dequeue = function(ele){ return items.shift();}
    this.enqueue = function(ele){ return items.push();}
    this.isEmpty = function(){ return items.length == 0;};
    this.size = function(){return items.length;};
    this.clear = function(){itmes = [];};
    this.show = function(){console.log( items.toString())};
}
//优先队列

3,链表——有序元素组合,但不是连续存放,每节点包含自身和下一个节点的指针

function LinkedList(){
    var Node = function (ele){
        this.element = ele;
        this.next = null;
    };
    var head = null;        //始终是第一个元素节点;
    var length =0;
    this.append = function(ele){
        var node = new Node(ele);
        var current;
        if(head ===null){
            head = node;        //如果没有元素,就直接放在对象里,且属性的next永远是null;
        }else{
            current = head;   //如果不是空的对象,就循环对象的元素,直最后的元素是next 是null;
            while(current.next){
                current = current.next;
                }
              current.next = node;
            }
             length++;
     };
     //这种方法只能从头开始一个一个添加;
    this.insert = function(position,ele){
        if(position>= 0&& position <= length{
            var node = new Node(),
            current =head,
            previous ,
            index = 0;
            if(position ===0){
                previous = current;
                head = node;
            }else{
                while(index++ < positon){
                    previous = current;
                    current = current.next;
                }
                length++;
                return true;
            }else{
                return false;
            }
      };
    this.removeAt = function(position){ 
        if(position > -1 && position < length){
            var current = head,
            previous,
            index = 0;
            if(position == 0){
                head = current.next;
            }else{
                while(index++<position){
                    previous = current;
                    current = current.next;
                }
                previous.next = current.next;
            }
            length --;
            return current.ele;
        }else{
            return null;
        }       
    };
    this.indexOf = function (ele){
        var current = head,
        index = -1;
        while(current){
            if(ele ===current.ele){
                return index;
            }
            index ++;
            current = current.next;
        }
        return -1;
     };
    this.isEmpty = function(){
        return length ===0;
     };
    this.size = function(){
        return length;
     };
    this.toString = function(){
        var current = head,
        string = '';
        while(current){
            string = current.ele;
            current = current.next;
        }
        return string;
     };
    this.print = function (){ };
    
}

4,集合——无序且唯一的项组成的(数学概念的有限集合不重复)值-值存储,区分对象

function Set(){
    var items = {};
    this.has = function(value){
        return items.hasOwnProperty(value);
    };
    this.add =function(value){
        if(!this.has(value)){
            items[value] = value;
            return true;
        }
        return false;
    };
    this.remove = function(){
        if(items.has(value)){
            delete items[value];
            return true;
        }
        return false;
    };
    this.clear = function(){
        items = {};
    };
    this.size = function(){
        return Object.keys(items).length;
    };
    this.values = function (){
        return Object.keys(items);
    };
    this.union = function(otherset){        //合并两个集合,返回新的集合,合集;
        var unionset = new Set();
        var values = this.values();
        for(var i=0;i<values.length;i++){
            unionset.add(values[i]);
        }
        values = otherset.values();
         for(var i=0;i<values.length;i++){
            unionset.add(values[i]);
        }
        return unionset;
    };
    this.intersection = function(otherset){    //返回两个集合的交集
        var interset = new Set();
        var values = this.values();
        for(var i =0;i<values.length;i++){
            if(otherset.has(values[i])){
                interset.add(values[i]);
            }
        }
        return interset;
    };
    this.diff = function(otherset){        //返回两个集合的差集
        var diffset = new Set();
        var values = this.values();
        for(var i =0;i<values.length;i++){
            if(!otherset.has(values[i])){
                diffset.add(values[i]);
            }
        }
        return diffset;
    };
    this.sub = function(otherset){        //判断是否是子集;
        if(this.size()>otherset.size()){
            return false;
        }else{
            var values = this.values();
             for(var i =0;i<values.length;i++){
            if(!otherset.has(values[i])){
               return false;
            }
        }
        return true;
        }
    }
}

5,字典——不重复的存储,键-值保存;

function Dictionary(){
    var items = {};
    this.has = function(key){
        return key in 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.get = function(key){
         return this.has(key)?items[key]:undefined;
     };
     this.values = function(){
         var values  = [];
         for(var k in items){
             if(this.has(k)){
                 values.push(itmes[k]);
             }
         };
         return values;
     };
     this.getItems = function(){
         return items;
     };
      this.clear = function(){
        items = {};
    };
    this.size = function(){
        return Object.keys(items).length;
    };
    this.values = function (){
        return Object.keys(items);
    };
}

6,散列表——通过函数计算出键的位置,也就是说保存的键值不是我们提供的原始键;

function HashTable(){
    var table = [];
    var loseHashCode = function(key){        //散列函数
        var hash = 0;
        for(var i = 0;i<key.length;i++){
            hash +=key.charCodeAt(i);
        }
        return hash % 37;
    };
   var ValuePair = function(key,value){    //用于确定key重复时使用
        this.key = key;
        this.value =value;
        this.toString = function(){
            return '['+this.key+'-'+this.value+']'
        }
    }
    //更好的散列函数
    var HashCode = function(key){
        var hash = 5381;
        for(var i =0;i<key.length;i++){
            hash = hash*33 + key.charCodeAt(i);
        }
        return hash%1013
    };
    //以上数字都是特殊的数字,比较不容易冲突
    this.put = function(key,value){
        var position = loseHashCode(key);
      if( table[position] == undefined){
          table[position]= new ValuePair(key,value);
      }else{
          var index = ++position;
          while(table[index] != undefined){
              index ++;
          }
          table[index] = new ValuePair(key,value);
      }
    };
    this.get = function(key){
        var position = loseHashCode(key);
      if( table[position] !== undefined){
        if(table[position].key ===key){
            return table[position].value;
          }else{
          var index = ++position;
          while(table[index] != undefined || table[index].key !==key){
              index ++;
          }
         if(table[index].key === key){
             return table[index].value;
             }
          }
      }
      return defined;
    };
    this.remove= function(key){
        table[index] = undefined;
    };
}

7,树——非顺寻数据结构

function BinarySearchTree(){
    var Node = function(key){
        this.key = key;
        this.left = null;
        this.right = null;
    };
    var root =null;
    var insertNode = function(node,newNode){
        if(newNode.key < node.key){
            if(node.left === null){
                node.left = newNode;
            }else{
                insertNode(node.left,newNode);
            }
        }else{
            if(node.right ===null){
                node.right = newNode;
            }else{
                insertNode(node.right,newNode);
            }
        }
    };
    this.insert = function(key){
        var newNode  = new Node(key);
        if(root ===null){
            root = newNode;
        }else{
            insertNode(root,newNode)
        }
    };
    var inOrderTraverseNode =function(node,callback){        //中序遍历
        if(node !== null){
            inOrderTraverseNode (node.left,callback);
            callback(node.key);
            inOrderTraverseNode(node.right,callback);
        }
    };
    this.inOrderTraverse = function(callback){
        inOrderTraverseNode (root,callback)
    };
    var printNode = function(value){        //回掉函数
        console.log(value);
    };
    this.preOrderTraverse = function(callback){
        preOrderTraverseNode(root,callback);
    };
    var preOrderTraverseNode = function(node,callback){    //先序遍历
        if(node !== null){
            callback(node.key);
            preOrderTraverseNode(node.left,callback);
            preOrderTraverseNode(node.right,callbck)
        };
    };
      this.postOrderTraverse = function(callback){
        postOrderTraverseNode(root,callback);
    };
    var postOrderTraverseNode = function(node,callback){    //后序遍历
        if(node !== null){
            preOrderTraverseNode(node.left,callback);
            preOrderTraverseNode(node.right,callbck);
               callback(node.key);
        };
    };
    this.min = function(){
        return minNode(root)
    };
    var minNode = function(node){
        if(node){
            while(node && node.left !=null){
                node = node.left;
            }
            return node.key;
        }
        return null;
    };
     this.max= function(){
        return maxNode(root)
    };
    var maxNode = function(node){
        if(node){
            while(node && node.right !=null){
                node = node.right;
            }
            return node.key;
        }
        return null;
    };
    this.search = function(key){
        return searchNode(root,key);
    };
    var searchNode = function(node,key){
        if(node === null){return false;}
        if(key<node.key){return searchNode(node.left,key)}
        else if(key>node.key){return searchNode(node.right,key)}
        else{return true;}
    };
    this.remove = function(key){
        root = removeNode(root,node);
    };
    var removeNode = function(node,key){
        if(node ===null){ return null; };
        if(key < node.key){ 
            node.left = removeNode(node.left,key);
            return node;
        }else if(key>node.key){
            node.right = removeNode(node.right,key)
        }else{
            if(node.left ===null && node.right ===null){
                node =null;
                return node;
            }
            if(node.left ===null){
                node = node.right;
                return node;
            }else if(node.right ===null){
                node = node.left;
                return node;
            };
            var aux = findMinNode(node.right);
            node.key = aux.key;
            node.right = removeNode(node.right,aux.key);
            return node;
        }
    }
    
}

8,图——G = (V ,E)由边和顶点组成

function Graph(){
    var  vertices = [];
    var adjList = new Dictonary();
    this.addVertex = function(v){
        vertices.push(v);
        adjList.set(v,[]);
    };
    this.addEdge = function(v,w){
        adjList.get(v).push(w);
        adjList.get(w).push(v);
    };
    this.toString = function(){
        var s = '';
        for(var i=0;i<vertices.length;i++){
            s+=vertices[i] + '->';
            var neighbors = adjList.get(vertices[i]);
            for(var j =0;j<neighbors.length;j++){
                s+=neighbors[j] + ' ';
            }
            s+='\n';
        }
        return s;
    };
    var initializeColor = function(){
        var color = [];
        for(var i=0;i<vertices.length;i++){
            color[vertices[i]] = 'white';
        };
        return color;
    };
    this.bfs = function(v,callback){        //广度搜索,用颜色标记
        var color =  initializeColor();
        queue = new Queue();
        queue.enqueue(v);
        while(!queue.isEmpty()){
            var u = queue.dequeue();
            neighbors = adjList.get(u);
            color[u] = 'grey';
            for(var i= 0;i<neighbors.length;i++){
                var w = neighbors[i];
                if(color[w] ==='white'){
                    color[w] = 'grey';
                    queue.enqueue(w);
                }
            }
            color[u] = 'black';
            if(callback){
                callback(u);
            }
        }
    };
    this.BFS = function(v){
        var color= initializeColor,
        queue= new Queue(),
        d = [],
        pred = [];
        queue.edqueue(v);
        for(var i =0;i<vertices.length;i++){
            d[vertices[i]] = 0;
            pred[vertices[i]] = null;
        }
        while(!queue.isEmpty()){
            var u = queue.dequeue();
            var neighbors = adjList.get(u);
            color[u]= 'grey'
            for(i = 0;i<neighbors.lenght;i++){
                var w = neighbors[i];
                if(color[w] === 'white'){
                    color[w] = 'grey';
                    d[w] = d[u] + 1;
                    pred[w] = u;
                    queue.enqueue(w);
                }
            }
            color[u] = 'black';
        }
        return {
            distance :d,
            predecessors : pred
        }
    };
   this.dfs = function(callback){        //深度优先
        var color = initializeColor();
        for(var i = 0;i<vertices.length;i++){
            if(color[vertices[i]] === 'white'){
                dfsVisit(vertices[i],color,callback);
            }
        }
    };
    var dfsVisiit = function(u,color,callback){
        color[u] = 'grey';
        if(callback){callback(u)};
        var neighbors = adjList.get(u);
        for(var i =0;i<neighbors.length;i++){
            var w = neighbors[i];
            if(color[w] ==='white'){
                dfsVisit(w,color,callback);
            }
        }
        color[u] = 'black';
    }
 }

数组排序的方法

function ArrayList(){
    var array = [];
    this.insert = function(item){array.push(item)};
    this.toString = function(){return array.join()};
    var swap = function(index1,index2){        //交换数组位置的方法
        var temp = array[index1];
        array[index1] = array[index2];
        array[index2] = temp;
    };
    this.bubbleSort = function(){        //冒泡排序从小到大
        var length = array.length;
        for(var i =0;i<length;i++){
            for(var j = 0;j<lenght-1;j++){
                if(array[j]>array[j+1]){
                    swap(j,j+1);
                }
            }
        }
    };
    this.selectionSort = function(){        //选择排序,选择最小值放在前面;
        var length = array.length;
        var indexMin;
        for(var i= 0;i<lenght;i++){{
            indexMIn = i;
            for(var j = i;j<length;j++){
                if(varay[indexMin] > array[j]){
                    indexMin = j;
                }
            }
            if(i ! = indexMin){
                swap(i,indexMin)
            }
        }
    }
    this.insertionSort = function(){        //插入排序;
        var length= array.length;
        var j,temp;
        for(var i = 0;i<lenght;i++){
            j = i;
            temp = array[i];
            while(j>0 && array[j-1] >temp){
                array[j] ==array[j-1];
                j--;
            }
            array[j] = temp;
        }
    }
    this.mergeSort = function(){
        array = mergeSortRec(array)
    };
    var mergeSortRec = function(array){
        var length = array.length;
        if(length ===1){
            return array;
        }
        var mid = Math.floor(length/2);
        var left = array.slice(0,mid);
        var right = array.slice(mid,length);
        return merge(mergeSortRec(left),mergeSortRec(right))
    };
    var merge = function(left,right){
    var result = [];
    var il = 0,ir = 0;
    while(il<left.length && ir<right.length){        //归并排序
        if(left[il]<right[ir]){
            result.push(left[il++])        
    }else{
        result.push(right[ir++])
        }
    }
    while(il<left.length){
        result.push(left[il++])
    }
    while(ir<right.length){
        result.push(right[il++])
    }
    return result;
    };
    this.quickSort = function(){        //快速排序
    quick(array,0,array.length-1)
};
var quick = function(){
    var index;
    if(array.length > 1){
        index = partition(array,left,right);
        if(left<idnex -1){
            quick(array,left,index-1)
        }
        if(index<right){
            quick(array,index,right);
        }
    }
};
var partition = function(){
    var pivot = array[Math.floor(right + left)/2],
    i= left,j =right;
    while(i<=j){
        while(array[i]<pivot){
            i++;
        }
        while(array[j]<pivot){
            j--;
        }
    if(i<=j){
        swap(array,i,j);
        i++;
        j--;
        }        
    }
    return i;
    };
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值