/*Update/
block 引用>I agree with the answers to check for
newVal
's existence... but if you had to choose one of the options, which is the less of the evils?我正在浏览一个教程,看到下面的代码使用了#1。我相信我有这个权利......会发生什么如果
newVal
通过更新数据库。如果 !not 则退出函数。我已经列出了我想到的变体...我的问题是最好使用什么,为什么或者是否有更好的方法没有列出? https://code.tutsplus.com/courses/real-time-web-apps-with-angularjs-and-firebase/lessons/on-value我正在做的教程是首先将 ng-model message.text 设置为数据库值 - 然后使用 watch 更新该值。我相信 !newVal 是在输入值之前阻止它更新。直接引用:“确保新值不是未定义的,因为当页面加载时新值是未定义的。”
- 如果有空白返回+没有其他
$scope.$watch('message.text', function(newVal){ if (!newVal){return;} childRef.update({ text: newVal }); });
- if 有空白 return + else
$scope.$watch('message.text', function(newVal){ if (!newVal){return;} else{ childRef.update({ text: newVal }); } });
- if 没有返回值并使用 else
$scope.$watch('message.text', function(newVal){ if (!newVal){} else{ childRef.update({ text: newVal }); } });
- if 没有 return 也没有 else - 我认为这不起作用
$scope.$watch('message.text', function(newVal){ if (!newVal){} childRef.update({ text: newVal }); });
最佳答案
如果陈述应尽可能使用肯定句,则不会那么困惑。
$scope.$watch('message.text', function(newVal) {
if(newVal) {
childRef.update({
text: newVal
});
}
});
我将你的例子解释为:
如果不是 newVal 则不执行任何操作,如果不是则不是 newVal 执行某些操作
而我将我的示例解释为:
如果 newVal 做某事
更容易理解。
==============================
关于是否使用return。没有必要,因为javascript将默认返回未定义;
关于javascript - 在 If/Else 中你应该使用空白返回来退出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34166735/