亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

基于循環的擴展算法

基于循環的擴展算法

墨色風雨 2023-11-02 20:17:57
我的算法計算通過 DOM 的路徑。它從給定的組件開始并沿樹向上。每次父組件具有特定屬性時,算法都會將其值添加到路徑中。_computePath(aComponent) {  let result = '';  let parent = aComponent.parentNode;  while (parent.tagName !== 'MY-ROOT-COMPONENT') {    if (parent.hasAttribute('my-attribute')) {      result = `/${parent.getAttribute('my-attribute')}${result}`;    }    parent = parent.parentNode;  }  return result;}在我的應用程序的其他部分,我需要一個稍微不同的版本。_computePath(aComponent) {  let result = '';  let parent = aComponent.parentNode;  while (parent.tagName !== 'MY-ROOT-COMPONENT') {    if (parent.tagName === 'SPECIAL-COMPONENT') {      result = null;      break;    }    if (parent.condition === 'special') {      result = null;      break;    }    if (parent.hasAttribute('my-attribute')) {      result = `/${parent.getAttribute('my-attribute')}${result}`;    }    parent = parent.parentNode;  }  return result;}如何在不重復代碼的情況下擴展第一個循環的算法?可能有一個非常簡單的解決方案,但不知何故我無法弄清楚。
查看完整描述

1 回答

?
慕神8447489

TA貢獻1780條經驗 獲得超1個贊

讓函數接受回調來測試導致其中斷的條件。


_computePath(aComponent, stopfun = parent => false) {

  let result = '';

  let parent = aComponent.parentNode;


  while (parent.tagName !== 'MY-ROOT-COMPONENT') {

    if (stopfun(parent)) {

      result = null;

      break;

    }


    if (parent.hasAttribute('my-attribute')) {

      result = `/${parent.getAttribute('my-attribute')}${result}`;

    }

    parent = parent.parentNode;

  }


  return result;

}


let result1 = obj1._computePath(component1); // no extra stop check

let result2 = obj2._computePath(component2, parent => parent.tagName === 'SPECIAL-COMPONENT' || parent.condition === 'special');


查看完整回答
反對 回復 2023-11-02
  • 1 回答
  • 0 關注
  • 125 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號