建立數組的方法有兩種;node
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]),對數組的每一個元素都執行函數app
在CHROME中輸出如上,函數默認有三個參數
1,數組元素
2,元素索引
3,整個數組ide
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;post
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;ui
3,Array.map(callback,[this.obj])和Array.filter(callback,[this.obj]);
返回新的數組this
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的返回值;spa
//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; }; }