-
隔江千里
给出totalValue初始值,现在它正在添加数字undefined,结果是NaNconst valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]const validateCred = (arr) => {let totalValue = 0 for (let i = arr.length - 1; i >= 0; i--) { let number = arr[i] *2 if (number > 9) { totalValue += number - 9 } else { totalValue += number } } return totalValue}console.log(validateCred(valid1))你也可以使用Array.reduce这样的方法const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]const totalValue = valid1.reduce((acc, num) => { let number = num * 2 if (number > 9) { acc += number - 9 } else { acc += number } return acc},0)console.log(totalValue)
-
HUWWW
totalValue在迭代之前将 的值设置为 0 通过建立totalValue数字来解决问题。还有其他方法可以做到这一点,但我认为这是合适的。const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]//trying to loop through the array and sum all the array values in totalValue variableconst validateCred = (arr) => {let totalValue = 0; for (let i = arr.length - 1; i >= 0; i--) { let number = arr[i] *2; if (number > 9) { totalValue += number - 9 } else { totalValue += number } } return totalValue}console.log(validateCred(valid1))
-
www说
您的 totalValue 未初始化。const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];const validateCred = (arr) => { let totalValue = 0; for (let i = arr.length - 1; i >= 0; i--) { let number = arr[i] * 2 if (number > 9) { totalValue += number - 9 } else { totalValue += number } } return totalValue}console.log(validateCred(valid1))