返回 1 和返回 0 在 Javascript 中的角色
The role of return 1 and return 0 in Javascript
这是代码
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");
}
这些0
和1
的真正用途很难猜测。它们可能由调用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(即使我们每次都这样做)。它真的只是更短。
相关文章:
- 节点导出返回一个空对象
- ES6构造函数返回基类的实例
- 监视函数从服务返回不起作用,但作用域函数起作用
- 控制台返回var不是't定义,但它是
- 从函数返回角度承诺
- Javascript返回值只在循环中返回一次
- 从控制器返回后Ajax启动事件激发
- CKFinder 3为所选文件返回错误的URL
- 如何在d3.js中返回路径的y坐标
- 如何从jquery函数返回变量
- Angular js-返回一个包含类似
- JSONP请求返回结果,但也触发error_callback
- 如何使用Spring MVC将Facebook返回的响应数据保存在Java类中
- 从HTTPGET返回一个自定义对象列表,以便在Angular 2应用程序中使用
- JS验证ajax返回的html中的表单数据
- 使用谷歌应用程序脚本将服务器端数据表返回到客户端
- AJAX:$_GET不返回任何值
- 返回 1 和返回 0 在 Javascript 中的角色
- AJAX调用CSV文件返回?对于某些角色
- 当旋转角色时,它会旋转一定的数量,然后返回