递归:递归就是自己调自己, var ids = [34112, 98325, 68125]; (function sendRequest(){ var id = ids.shift(); if(id){ $.ajax({url: "/get", data: {id}}).always(function(){ //do sth. console.log("finished"); sendRequest(); }); } else { console.log("finished"); } })(); dom树,用递归的方法查找实现dom的功能: function getElementById(node, id){ if(!node) return null; if(node.id === id) return node; for(var i = 0; i < node.childNodes.length; i++){ var found = getElementById(node.childNodes[i], id); if(found) return found; } return null; } getElementById(document, "d-cal"); 非递归:function getByElementId(node, id){ //遍历所有的Node while(node){ if(node.id === id) return node; node = nextElement(node); } return null; } function getByElementId(node, id){ //遍历所有的Node while(node){ if(node.id === id) return node; node = nextElement(node); } return null; } 依次遍历所有的DOM结点,改成一个while循环 function nextElement(node){ if(node.children.length) { return node.children[0]; } if(node.nextElementSibling){ return node.nextElementSibling; } while(node.parentNode){ if(node.parentNode.nextElementSibling) { return node.parentNode.nextElementSibling; } node = node.parentNode; } return null; } 还是用深度遍历,先找当前结点的子结点,如果它有子结点,则下一个元素就是它的第一个子结点,否则判断它是否有相邻元素,如果有则返回它的下一个相邻元素。如果它既没有子结点,也没有下一个相邻元素,则要往上返回它的父结点的下一个相邻元素,相当于上面递归实现里面的for循环的i加1. 复杂选择器的查DOM: 如实现一个document.querySelector: document.querySelector(".mls-info > div .copyright-content") set和map的哈希实现:var set = new Set(); //数据为20个数 var data = [3, 62, 38, 42, 14, 4, 14, 33, 56, 20, 21, 63, 49, 41, 10, 14, 24, 59, 49, 29]; for(var i = 0; i < data.length; i++){ set.add(data[i]); } function ComputeIntegerHash(key, seed) { var hash = key; hash = hash ^ seed; //seed = 505553720 hash = ~hash + (hash << 15); // hash = (hash << 15) - hash - 1; hash = hash ^ (hash >>> 12); hash = hash + (hash << 2); hash = hash ^ (hash >>> 4); hash = (hash * 2057) | 0; // hash = (hash + (hash << 3)) + (hash << 11); hash = hash ^ (hash >>> 16); return hash & 0x3fffffff; } 数字进行各种位运算,得到一个比较随机的数,然后对这个数对行散射 var capacity = 64; var indexes = []; for(var i = 0; i < data.length; i++){ indexes.push(ComputeIntegerHash(data[i], seed) & (capacity - 1)); //去掉高位 } console.log(indexes) 数组去重: function uniqueArray(arr){ return Array.from(new Set(arr)); } function uniqueArray(arr){ for(var i = 0; i < arr.length - 1; i++){ for(var j = i + 1; j < arr.length; j++){ if(arr[j] === arr[i]){ arr.splice(j--, 1); } } } return arr; }
function uniqueArray(arr){ var retArray = []; for(var i = 0; i < arr.length; i++){ if(retArray.indexOf(arr[i]) < 0){ retArray.push(arr[i]); } } return retArray; }