【问题标题】:TestDome Challenge Closest RelativeTestDome 挑战最近的亲戚
【发布时间】:2022-07-09 21:25:16
【问题描述】:

我试图从 testdome 解决这个挑战,但我被卡住了。 以下 HTML 表示一个家谱:

<James>
  <Dave></Dave>
  <Mike></Mike>
  <Sarah></Sarah>
</James> 

实现closestRelative函数,以便在传递父HTML元素时,该函数返回名称与relativeName匹配的父级最近的亲戚,并遵守以下规则:

parent 参数是 HTML 元素,其最近的亲戚将是其后代。 每个家庭成员,包括孩子,也可能是一个或多个孩子的父母。 与孙辈相比,孩子与父母的关系更密切。 如果同一代中的几个孩子有相同的名字,那么树中的第一个孩子被认为是近亲。 如果没有找到匹配的亲戚,该函数应返回 null。 例如,下面的代码应该为给定的家谱打印“MIKE”:

let parent = document.getElementsByTagName('James')[0];
let relative = closestRelative(parent, 'Mike');
console.log(relative && relative.tagName); // prints MIKE

我搜索了答案,我发现只有 jquery 方法可以解决这个问题。我不知道 Jquery,所以我正在尝试用 js 解决它。 这是我的代码:

function closestRelative(parent, relativeName) {
  result = parent.find(relativeName);
  if (result.length === 1 ){
    return result
  } else if (result.length > 1) {
      let lowest = 0 ;
      let lowestIdx = 0;
      result.forEach( function (idx, item) {
        if(idx === 0 ){
          lowest = item.closest().index(parent);
        } else {
          if (item.closest().index(parent) < lowest) {
            lowestIdx = idx;
            lowest = item.closest().index(parent);
          }
        }
      });
    return ([result[lowestidx]]);
  }
  else {
    return ([]);
  
} 

【问题讨论】:

标签: javascript closest challenge-response


【解决方案1】:

我在这个网站上找到了正确的答案! https://khw1031.github.io/posts/closest-relative-testdome/

function closestRelative(parent, relativeName) {
  const queue = [...parent.children];
  const tagName = relativeName.toUpperCase();
  let el;
  
  while (queue.length > 0 ){
    el = queue.shift();
    if (el.tagName === tagName) return el;
    if(!el.hasChildNodes()) {continue ;}
    
    for (const childEl of el.children) {
      queue.push(childEl)
    }
  }
  return null
}

【讨论】:

    【解决方案2】:

    使用这个

    function closestRelative(parent, relativeName) {
      // Implement function here
      const queue = Array.from([...parent[0].children]);
      const tagName = relativeName.toUpperCase();
      let el;
      
      while (queue.length > 0 ){
        el = queue.shift();
        if (el.tagName === tagName) 
          return $(el.tagName);
        if(!el.hasChildNodes()) {continue ;}
        
        for (const childEl of el.children) {
          queue.push(childEl)
        }
      }
      return null
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 2019-11-06
      • 2020-10-12
      • 1970-01-01
      • 2013-12-21
      • 1970-01-01
      相关资源
      最近更新 更多