3 回答
TA贡献1906条经验 获得超10个赞
给出totalValue初始值,现在它正在添加数字undefined,结果是NaN
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))
你也可以使用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)
TA贡献1874条经验 获得超12个赞
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 variable
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))
TA贡献1775条经验 获得超8个赞
您的 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))
添加回答
举报