返回 1 和返回 0 在 Javascript 中的角色

The role of return 1 and return 0 in Javascript

本文关键字:返回 角色 Javascript      更新时间:2023-09-26

这是代码

function toDo(day){
 // 1. check IF day is saturday OR sunday
  if (day==="saturday"||day==="sunday"){
  // 2. return the weekendChore function    
      return weekendChore();
  }
  else{
  // 3. otherwise return the weekdayChore function.
      return weekdayChore();
  }
}
      // These are the functions we will return:
function weekendChore(){
  alert("Weekend: walk 9am, feed at 4pm, walk at 10pm");
  return 1;
}
function weekdayChore(){
  alert("Weekday: feed at 12pm, walk at 1pm");
  return 0;
}

我是Javascript的新手,正在尝试学习。我搜索了一下,没有找到上面提到的代码中返回 1 和返回 0 的作用的正确解释。你能解释一下吗?另外,你能用其他一些例子重播吗?谢谢

相当于

function toDo(day){
 // 1. check IF day is saturday OR sunday
  if (day==="saturday"||day==="sunday"){
  // 2. return the weekendChore function    
      weekendChore();
      return 1;
  }
  else{
  // 3. otherwise return the weekdayChore function.
      weekdayChore();
      return 0;
  }
}
      // These are the functions we will return:
function weekendChore(){
  alert("Weekend: walk 9am, feed at 4pm, walk at 10pm");
}
function weekdayChore(){
  alert("Weekday: feed at 12pm, walk at 1pm");
}

这些01的真正用途很难猜测。它们可能由调用toDo的代码使用。

有时能够尽快返回是件好事(特别是如果您经常使用函数)。不过,我无法在这里解释某些情况,因为它们每个只被调用一次。

下面是一个示例,说明为什么多次调用它很有用:

var lastError;
function doStuff(username) {
    if (users.create(username)) {
        if (users[username].setActive(true)) {
            return true;
        } else {
            return setError('Could not set user to active');
        }
    } else {
        return setError('Could not create user');
    }
}
function setError(error) {
    lastError = error;
    return false;
}
if (registerUser('MyUser')) {
    alert('Yay!');
} else {
    alert('An error happened: ' + lastError);
}

..与此相比:

function doStuff(username) {
    if (users.create(username)) {
        if (users[username].setActive(true)) {
            return true;
        } else {
            lastError = 'Could not set user to active';
            return false;
        }
    } else {
        lastError = 'Could not create user';
        return false;
    }
}

这只是意味着每次我们需要设置错误时,我们都必须返回 false(即使我们每次都这样做)。它真的只是更短。