简体   繁体   English

我们可以不用javascript编写IF语句吗

[英]Can we write IF statement without else in javascript

I wrote some code to create an simple todo app in angular js. 我写了一些代码来用angular js创建一个简单的todo应用。 I have the following function code to remove the tasks from the list. 我有以下功能代码从列表中删除任务。

Javascript code JavaScript代码

$scope.deleteTask =  function(){
    $scope.tasks.splice(this.$index, 1);
    if($scope.tasks.length < 1){
        $scope.noTask = true;
    }     
};

HTML code HTML代码

    <li ng-repeat="task in tasks track by $index">{{task}}  <button ng- click="deleteTask()">x</button></li> </li>
    <p ng-show="noTask">No Tasks Available </p>

I wanted to show a message when there are no tasks in the list. 我想在列表中没有任务时显示一条消息。 i have achieved this using "if" statement. 我已经使用“ if”语句实现了这一点。 but i don't need an else here. 但我这里不需要别的。 i am not sure whether its the right way. 我不确定这是否正确。 what will be the proper way to achieve this 什么是实现这一目标的正确方法

There is nothing wrong in your code. 您的代码没有错。
You can use if statement without else. 您可以使用if语句,而无需其他。
But for your case i recommended you to write your code as follow 但是对于您的情况,我建议您按以下方式编写代码
Which remove some of your extra code 哪些删除了一些额外的代码

<p ng-show="tasks.length==0">No Tasks Available </p>

As in any (?) other programming language you can omit else part if it's empty. 正如在任何(?)其他的编程语言,你可以忽略else部分,如果它是空的。

Just make sure that if you assign some value in if (true) than if it's not executed have default value for that variable: 只要确保在if (true)分配一些值if (true)如果未执行则分配该值if (true)具有该变量的默认值:

var test = false;

if (Math.rand() < 0.5) {
    test = true;
} 

Also there is shorthand for if else (where you can't omit else part): 还有if的shorthand (如果您不能忽略else部分):

var test = Math.rand() < 0.5 ? "True value" : "False value";

I wanted to show a message when there are no tasks in the list. 我想在列表中没有任务时显示一条消息。 i have achieved this using "if" statement. 我已经使用“ if”语句实现了这一点。 but i don't need an else here. 但我这里不需要别的。 i am not sure whether its the right way. 我不确定这是否正确。 what will be the proper way to achieve this 什么是实现这一目标的正确方法

Anyway you don't need an else statement you can use ng-if. 无论如何,您不需要else语句就可以使用ng-if。 The ng-if statement is also available without an else condition. ng-if语句也可以不带else条件。

You should be able to use this angular code: 您应该可以使用以下角度代码:

$scope.deleteTask =  function(){
    $scope.tasks.splice(this.$index, 1);
};

And this HTML part: 而这个HTML部分:

<li ng-repeat="task in tasks track by $index">{{task}}  
     <button ng-click="deleteTask()">x</button>
</li>
<p ng-show="noTask" ng-if="tasks.length == 0">No Tasks Available </p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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