這篇文章主要介紹了JavaScript怎么實現DOM樹的深度優先遍歷和廣度優先遍歷,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
// 非遞歸,首次傳入的node值為DOM樹中的根元素點,即html
// 調用:deep(document.documentElement)
function deep (node) {
var res = []; // 存儲訪問過的節點
if (node != null) {
var nodeList = []; // 存儲需要被訪問的節點
nodeList.push(node);
while (nodeList.length > 0) {
var currentNode = nodeList.pop(); // 當前正在被訪問的節點
res.push(currentNode);
var childrens = currentNode.children;
for (var i = childrens.length - 1; i >= 0; i--) {
nodeList.push(childrens[i]);
}
}
}
return res;
}
// 使用遞歸
var res = []; // 存儲已經訪問過的節點
function deep (node) {
if (node != null) { // 該節點存在
res.push(node);
// 使用childrens變量存儲node.children,提升性能,不使用node.children.length,從而不必在for循環遍歷時每次都去獲取子元素
for (var i = 0, childrens = node.children; i < childrens.length; i++) {
deep(childrens[i]);
}
}
return res;
}// 遞歸
var res = [];
function wide (node) {
if (res.indexOf(node) === -1) {
res.push(node); // 存入根節點
}
var childrens = node.children;
for (var i = 0; i < childrens.length; i++) {
if (childrens[i] != null) {
res.push(childrens[i]); // 存入當前節點的所有子元素
}
}
for (var j = 0; j < childrens.length; j++) {
wide(childrens[j]); // 對每個子元素遞歸
}
return res;
}
// 非遞歸
function wide (node) {
var res = [];
var nodeList = []; // 存儲需要被訪問的節點
nodeList.push(node);
while (nodeList.length > 0) {
var currentNode = nodeList.shift(0);
res.push(currentNode);
for (var i = 0, childrens = currentNode.children; i < childrens.length; i++) {
nodeList.push(childrens[i]);
}
}
return res;
}感謝你能夠認真閱讀完這篇文章,希望小編分享JavaScript怎么實現DOM樹的深度優先遍歷和廣度優先遍歷內容對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,遇到問題就找億速云,詳細的解決方法等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。