避免map函数内部无序列 [英] Avoid no-sequences inside map function

查看:35
本文介绍了避免map函数内部无序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要遍历的数组,所以我使用了地图原型.在每个元素的callbackfn内,我想运行几个表达式.

I have a array which I want to loop through so I use the map prototype. Inside the callbackfn of each element I want to run several expressions.

const test = [{ name: "foo", value: "1" }, { name: "bar", value: "2" }, { name: "x", value: "3" }]
  let found = false;
  test.map(name => (
    console.log(name.name),
    console.log(name.value),
    found = true
  ));

我已经用 分隔了每个表达式.尽管此命令可以正确运行并产生正确的结果,但我仍然可以看到意外使用逗号运算符无序列

I've separated each expression with a ,. Whilst this runs correctly and produces the correct results I can see my eslint saying Unexpected use of comma operator no-sequences

我打算在map函数中放置多个表达式吗?

How am I meant to put multiple expressions inside the map function?

推荐答案

我打算在map函数中放置多个表达式吗?

How am I meant to put multiple expressions inside the map function?

使用花括号:

test.map(name => {
   console.log(name.name)
   console.log(name.value)
   found = true
});

尽管 map 看起来并不像其他人指出的那样是正确的选择-看起来您应该使用 filter ,但是相同的规则适用于多个语句.

Though map doesn't look the right choice for this as pointed out others - looks like you should use filter, but the same rules apply for multiple statements.

普通括号是隐含回报"的简写,如果函数仅包含一个表达式,则可以省略 {} return 关键字.实际上,您通常也可以省略括号!

Normal brackets are a shorthand for 'implied return', where you can omit the {} and the return keyword if your function only contains one expression. In fact, you can usually omit the brackets too!

所以这些是等效的:

test.filter(name => {
    let found = false
    if(name==='sarah'){
       found = true
    }
    return found 
}

test.filter(name => name === 'sarah')

这篇关于避免map函数内部无序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆