简体   繁体   中英

Reduce function returning assignment is throwing error (ESLint issue: no-return-assign)

My code (which works):

const calculateBalance = (coins) => {
  console.log('coins', coins);
  return coins.reduce((bal, coin) => (bal += parseInt(coin.balance)), 0);
};

Basically I just want to add up all the coin balances in my portfolio, however I'm getting an eslint error.

Arrow function should not return assignment.

在此处输入图片说明

Googling I found this: https://eslint.org/docs/rules/no-return-assign

One of the interesting, and sometimes confusing, aspects of JavaScript is that assignment can happen at almost any point. Because of this, an errant equals sign can end up causing assignment when the true intent was to do a comparison. This is especially true when using a return statement.

Here they have an example of what to do:

function doSomething() {
    return (foo = bar + 2);
}

However that is what I implemented, but eslint is still complaining... is there a way to update my code block above to make it pass?

From the specs. (here MDN )

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.


As your bal is your accumulator , simply do bal + parseInt(coin.balance)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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