Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 修复在reduce函数中添加到累加器时ESLint no plusplus和no param REASign linter错误_Javascript_Typescript_Eslint - Fatal编程技术网

Javascript 修复在reduce函数中添加到累加器时ESLint no plusplus和no param REASign linter错误

Javascript 修复在reduce函数中添加到累加器时ESLint no plusplus和no param REASign linter错误,javascript,typescript,eslint,Javascript,Typescript,Eslint,在TypeScript中给出此代码: const res=arr.reduce((acc,cur)=>(cur.id?+acc:acc),0); 我该如何阻止linter抛出这两个错误 (参数)acc:使用了数字一元运算符'++'。埃斯林特无普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯 分配给函数参数“acc”。eslint无参数

在TypeScript中给出此代码:

const res=arr.reduce((acc,cur)=>(cur.id?+acc:acc),0);
我该如何阻止linter抛出这两个错误

(参数)acc:使用了数字一元运算符'++'。埃斯林特无普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯普鲁斯

分配给函数参数“acc”。eslint无参数重新分配

回调函数接受累加器和当前值作为参数,并为下一次迭代返回累加器,如果没有下一次迭代,则返回累加器作为结果。没有理由改变任何论点

有,这就是为什么埃斯林特抱怨这一点,和

此外,不允许使用类似
++acc
的语法

由于一开始不需要对acc进行变异,两种错误的最小修复方法是:

const res=arr.reduce((acc,cur)=>(cur.id?acc+1:acc),0);
//~~~~~^~~将`++acc`替换为`+acc+1``
如果
cur.id
是真实的,则返回
acc
,增量为
1
,否则返回当前的
acc
。除了返回递增的
acc
之外,您的版本还对当前的
acc
进行了变异,但没有理由这样做


如果您正在使用ESLint,则必须了解规则。您不能编写ESLint抱怨的代码,然后又对ESLint为什么抱怨您的代码感到困惑。有自己的文章解释基本原理,列出备选方案,并解释如何调整或禁用规则

例如,您可以禁用
无参数重新分配
规则

  • 通过在文件顶部包含注释
    //eslint disable no param reassign
  • //eslint禁用下一行无参数重新分配
    用法上方的一行
  • //eslint禁用行无参数重新分配
    在使用后的行中
  • 或者在
    .eslintrc
    文件中禁用它

还有一些。您可以进一步简化功能,以避免以下情况:

const res=arr.reduce((acc,cur)=>acc+Number(布尔值(cur.id)),0);
这将具有相同的语义,但是仍然不太清楚应该是什么样的条件
cur.id
。最好的做法是使其更加明确(尤其是在TypeScript中),例如
cur.hasOwnProperty(“id”)
cur.id!==0
当前id!==“
,具体取决于当前id可能是什么。然后,不再需要
Boolean
调用;例如,如果要计算
arr
中有多少对象具有
id
自己的属性,请改用以下方法:

const res=arr.reduce((acc,cur)=>acc+Number(cur.hasOwnProperty(“id”)),0);
或者这个:

const res=arr.filter((cur)=>cur.hasOwnProperty(“id”).length;
如果您仍要使用原始支票,可以使用以下方法将代码缩短为以下代码之一:

const res=arr.reduce((acc,{id})=>acc+Number(Boolean(id)),0);
const res=arr.filter(({id})=>id).length;