Javascript 函数的意外结果

Javascript 函数的意外结果,javascript,function,return-value,Javascript,Function,Return Value,我有以下两个代码块,我正试图调试 function getSectionId(target){ let element = target; if(element.hasAttribute('id')){ console.log(element.id); return element.id; } else { getSectionId(element.parentElement); } }; 事件激发,函数运行,但上面给出了以下意外结果 //第一个

我有以下两个代码块,我正试图调试

function getSectionId(target){
  let element = target;
  if(element.hasAttribute('id')){
    console.log(element.id); 
    return element.id;
  } 
  else {
    getSectionId(element.parentElement);
  }
};
事件激发,函数运行,但上面给出了以下意外结果

//第一个覆盖部分(预计为这一部分。) //未定义(预期相同,但不相同。)


我一辈子也弄不明白为什么会发生这种情况。

问题是递归调用没有返回任何东西。 当您这样做时:

getSectionId(element.parentElement)

它会调用函数,也许有一天,会调用上面的if

if(element.hasAttribute('id')){
    console.log(element.id); 
    return element.id;
  }
将返回某些内容,但不会返回到以前的呼叫,因此您的主呼叫将不会返回任何内容,因此要解决此问题,您需要执行以下操作:

function getSectionId(target){
  let element = target;
  if(element.hasAttribute('id')){
    console.log(element.id); 
    return element.id;
  } 
  else {
    // add this return and your function will work correctly.
    return getSectionId(element.parentElement);
  }
};
基本上你有这样的东西:

函数递归不工作(n){
如果(n==5){
返回“某物”
}否则{
//你不归还任何东西,那么就不会有什么东西冒出来
递归不工作(n+1);
}
}
函数递归工作(n){
如果(n==5){
返回“某物”
}否则{
//我们还些东西
返回递归工作(n+1);
}
}
log(“NW:,recursiveNotWorking(1));

log(“Working:,recursiveWorking(1))
在第一个函数中没有
返回
,也没有检查
未定义
。此外,您不需要使用
元素
变量。没用。 也许这会奏效:

function getSectionId(target){
  if (typeof target === 'undefined') return null;
  if(target.hasAttribute('id')){
    console.log(target.id); 
    return target.id;
  } 
  return getSectionId(target.parentElement);
}

您需要返回递归调用的结果:

const getSectionId = target => {
  if (target.hasAttribute('id') {
    return target.id;
  }

  // You should also check that parentElement exist
  // Otherwise you might reach the root node and then parentElement could become null

  return getSectionId(target.parentElement);
};
Alos,这可以作为一行代码重新编写:

const getSectionId = t => t.id || getSectionId(t.parentElement)

您需要
else
块中返回递归调用的结果
const getSectionId = t => t.id || getSectionId(t.parentElement)