简体   繁体   中英

Code returns undefined instead of return value

I have string 101000 or 1010100 in which I am trying to replace 100 recursively using function remove data. The function removedata should return "yes" when string is empty and "no" when string is not empty while replacing it with value 100.

It works fine for string 1010100. It returns "no" but not for string 101000 where it becomes empty.

 console.log(removedata("1010100")); console.log(removedata("101000")); function removedata(data) { data = data.replace("100", ""); if (data.length == 0) { return "yes"; } else { if (data.indexOf("100") > -1 && data.length > 0) { removedata(data); } else { return "no"; } } } 

when 1010100 it returns no but when 101000 it returns undefined

You need to return the recursive call:

 console.log(removedata("1010100")); console.log(removedata("101000")); function removedata(data) { data = data.replace("100", ""); if (data.length == 0) { return "yes"; } else { if (data.indexOf("100") > -1 && data.length > 0) { return removedata(data); } else { return "no"; } } } 

Now it returns yes for the second one because all of the 100 s have been removed and the string is empty.

function removedata(data) {
  data = data.replace("100", "");
  if (data.length == 0) {
    return "yes";
  } else {
    if (data.indexOf("100") > -1 && data.length > 0) {
      removedata(data);                                     // This branch does not return anything
    } else {
      return "no";
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM