I am trying to learn JavaScript arrays and algorithms and for loops. I am trying to make a function, that takes an array as a parameter, and has to multiply each number in the array with the next number. I can't seem to figure out what I am missing.
It just returns the array
function xNumbers (arr) {
for (let i = 0; i < arr.lenght-1; i++) {
var num1 = arr[i]
var num2 = arr[i+1]
var result;
try {
if (typeof (num1) == 'string' || typeof (num2) == 'string') {
throw num1, "or", num2, "is not a number";
} else if (num2 == 0) {
throw 'Cant multiply with 0'
} else {
result = num1*num2
}
} catch (error) {
console.log(error);
result = NaN;
} finally {
arr[i] = result
}
}
return arr
}
console.log(xNumbers([2,3,4,5]));
// expected output 6, 12, 20 - doesn't work
you can use the following code.
function xNumbers (arr) {
arr = arr.map(x => Number(x))
result = new Array(arr.length -1)
for (let i = 0; i < arr.length-1; i++) {
result[i] = arr[i] * arr[i + 1]
}
return result
}
console.log(xNumbers([2,3,4,5]));