我需要帮助,将代码重构为ES6最佳做法,并通过以下ESLinting规则。下面是我的整个方法。这里的for循环就是问题。
formatNumber(val) {
if (!isFinite(val)) {
return val;
}
const valFloat = val.toString();
const decPos = valFloat.indexOf('.');
const intPart = (decPos === -1) ? valFloat : valFloat.substr(0, decPos);
const formattedNum = [];
// this needs refactoring
for (const ii in intPart) {
if (ii % 3 === 0 && ii !== 0) {
formattedNum.push();
}
formattedNum.push(intPart[intPart.length - 1 - ii]);
}
formattedNum.reverse();
return (decPos === -1) ? formattedNum.join('') : formattedNum.join('') + valFloat.slice(decPos, valFloat.length);
}
ESLint: The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype.(guard-for-in)
ESLint: for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array.(no-restricted-syntax)
首先,在精神上解析代码并不是特别好玩:如果您可以说出代码在做什么,而不是交给我们来解析,那将是有帮助的,尤其是当它做的事情很奇怪,就像循环遍历键中的键时一样。一个数组,对键进行计算,然后使用数组中的逆值。最非常规!
问题出在for..in
循环上,如ESLint documentation中所述。此ESLint规则要求,如果使用for..in
循环,请在每个键上运行Object.prototype.hasOwnProperty
,以确保它是所需对象的一部分,而不是来自向Object.prototype
添加属性的其他代码(或者,在这种情况下,也是String.prototype
)。这是明智的防御性编码。
所以您可以执行此操作:
for (const ii in intPart) {
if (!Object.prototype.hasOwnProperty.call(intPart, ii)) {
continue;
}
...
但是对我来说这不是一个很好的解决方案,实际上有可能以一种更好,更易于遵循的方式重构您的代码,该方式也可以解决此问题:
const formattedNum = intPart
.split('') // split the string into an array of digits
.reduceRight((acc, val, idx) => { // loop through the array with a reducer function, starting at the right
acc.unshift(val); // add the digit to the beginning of the output array
if (
idx && // if it's not the first item in the array (where idx === 0)
((intPart.length - idx) % 3 === 0) // and it is a multiple of three from the end of the array
) {
acc.unshift(','); // add a comma to the beginning of the array
}
return acc;
}, []);