javascript - 在 If/Else 中你应该使用空白返回来退出吗?

标签 javascript angularjs return return-type

/*Update/

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 是在输入值之前阻止它更新。直接引用:“确保新值不是未定义的,因为当页面加载时新值是未定义的。”

  1. 如果有空白返回+没有其他
$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/

    相关文章:

    javascript - NetSuite SuiteScript 2 - 通过搜索访问子列表

    C++ 成员函数即使删除了调用它的对象也能够访问数据

    assembly - x86 和 x64 中的 ret 指令有什么区别?

    javascript - 在Javascript中获取Java设置的cookie

    javascript - HTML5 Canvas 图像裁剪、调整大小和保存而不损失质量

    javascript - AngularJS 和 Bootstrap DatePicker 指令的工作示例?

    javascript - 如何在函数中使用 ng-tags-input 添加或删除标签

    angularjs - 如何根据特定请求禁用或停止 Angular BlockUI

    python - 如何在 Kivy 中返回布局内的小部件?

    javascript - jQuery 数据表清除标题中的单选按钮