0

我有一个格式化货币的函数:

export const formatDollar = (dollar) => {
  const format = function moneyFormat(val, sign = '$ ') {
    const pieces = parseFloat(val).toFixed(2).split('');
    let ii = pieces.length - 3;
    while ((ii -= 3) > 0) {
      pieces.splice(ii, 0, ',');
    }
    return sign + pieces.join('');
  };
  return format(dollar);
};

这部分导致 ESLint 错误:

while ((ii -= 3) > 0) { pieces.splice(ii, 0, ','); }

错误“while”语句中的意外分配 no-cond-assign

我应该如何编写此语句以使 ESLint 检查通过?

4

1 回答 1

2

表达式ii -= 3等价于ii = ii - 3并且可以替换为ii - 3 > 0。但是,由于在这种情况下它不再修改变量ii。您需要在循环中显式递减它。所以你可以像这样重写它:

while (ii > 3) { // or ii - 3 > 0
  ii = ii - 3;
  pieces.splice(ii, 0, ',');
}

几个测试:

const formatDollar = (dollar) => {
  const format = function moneyFormat(val, sign = '$ ') {
    const pieces = parseFloat(val).toFixed(2).split('');
    let ii = pieces.length - 3;
    while (ii > 3) {
      ii = ii - 3
      pieces.splice(ii, 0, ',');
    }
    return sign + pieces.join('');
  };
  return format(dollar);
};

console.log(formatDollar(12345678))
console.log(formatDollar(12345))
console.log(formatDollar(12))
console.log(formatDollar(.12))

于 2017-09-23T15:25:05.847 回答