Javascript 如何在javascript的箭头函数中使用if-else条件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37627712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:32:22  来源:igfitidea点击:

how to use if-else conditon in arrow function in javascript?

javascript

提问by avadhoot

I am new for Arrow function in java script. anybody please let me know is it possible to use if else condition in java script using arrow function.

我是 Java 脚本中箭头函数的新手。任何人请让我知道是否可以使用箭头函数在java脚本中使用if else条件。

回答by Matt Way

An arrow function can simply be seen as a concise version of a regular function, except that the returnis implied (among a few other subtle things you can read about here). One nice way to use an if/else is though a ternary. Take this regular function:

箭头函数可以简单地看作是常规函数的简明版本,除了它return是隐含的(您可以在此处阅读其他一些微妙的东西)。使用 if/else 的一种好方法是使用三元。以这个常规函数为例:

function(a){
    if(a < 10){
        return 'valid';
    }else{
        return 'invalid';
    }
}

The equivalent in an arrow function using a ternary is:

使用三元的箭头函数中的等效项是:

a => (a < 10) ? 'valid' : 'invalid'

回答by Douglas

As you've probably found, the body of an arrow function without braces can only be a single expression, so if statements are not allowed.

您可能已经发现,没有大括号的箭头函数的主体只能是一个表达式,因此不允许使用 if 语句。

Statements are allowed in arrow functions with braces though, like this:

但是,在带大括号的箭头函数中允许使用语句,如下所示:

const func = () => {
    if (...) ...
}

回答by Dr Fred

for a single 'if' condition you may use a shortcut syntax.

对于单个“if”条件,您可以使用快捷语法。

Imagine you need to execute a doThis() function only if a > 10 :

想象一下,只有当 a > 10 时,您才需要执行 doThis() 函数:

a => a > 10 && doThis()

回答by Shafie Mukhre

This is one way to do it that I found useful

这是我发现有用的一种方法

for this regular function

对于这个常规功能

function(a){
    if(a < 10){
        return 'valid';
    }
}

The equivalent in arrow function is

箭头函数中的等价物是

a => {
    if(a < 10){
        return 'valid';
    }
}

I found this useful when doing conditional mapping of an array data in React project. example as below

在 React 项目中对数组数据进行条件映射时,我发现这很有用。示例如下

function App(){
    const items = useFetch()
    return (
        <div>
            {items.map( (item) => {
                if (item[1]==='something'){
                    return (
                        <li>{item[2]}</li>
                    )
                }
            })}
        </div>
    )
}

回答by Azamantes

You need to know how arrow functions operate.

你需要知道箭头函数是如何运作的。

var foo = (value) => value;

Is the same as:

是相同的:

var foo = (value) => {
    return value;
}

Which is the same as:

这与以下内容相同:

function foo(value) {
    return value;
}

So as you can see there is nothing special about putting if-else inside arrow functions.

因此,正如您所看到的,将 if-else 放在箭头函数中并没有什么特别之处。