I made a function that sums the average of an array, but I'm having problems with lint, it talks about i++, I've tried [i += 1]; but it breaks my code. enter code here
function average(myArray) {
let i = 0;
let summ = 0;
if (myArray.length === 0) return undefined;
let ArrayVz = myArray.length;
while (i < ArrayVz) {
summ += myArray[i += 1];
if (typeof summ === 'string') return undefined;
}
return Math.round(summ / ArrayVz);
}
i++ and i += 1 give different results … which is why your linter is complaining about using i++ in the first place. It makes for confusing code.
You appear to want to take the value of i and then add one to it for the next loop.
i++ will so that, but i += 1 adds one before taking the new value.
Split your code out into separate statements to make it clearer (the order is explicit) and easier to maintain.
summ += myArray[i];
i += 1;
It would be more idiomatic to write it as a for loop instead of a while loop though.
I noticed, your not counting i up. I would use a for loop like this
function average(myArray) {
let i = 0;
let summ = 0;
if (myArray.length === 0) return undefined;
let ArrayVz = myArray.length;
for (let i = 0; i < ArrayVz.length; i++) {
summ += myArray[i];
if (typeof summ === 'string') return undefined;
}
return Math.round(summ / ArrayVz);
}
You can do this
function average(myArray) {
let i = 0;
let summ = 0;
if (myArray.length === 0) return undefined;
let ArrayVz = myArray.length;
for (let i = 0; i < ArrayVz.length; i++) {
summ += myArray[++i];
if (typeof summ === 'string') return undefined;
}
return Math.round(summ / ArrayVz);
}