简体   繁体   English

无法对 javascript 中的 for 循环内的值求和

[英]can't sum values inside a for loop in javascript

I believe this is a scope problem, but idk why it's not working.我相信这是一个 scope 问题,但我不知道为什么它不起作用。 I'm fairly new to js, tried checking the documentation but still couldn't solve it我对js还很陌生,尝试检查文档但仍然无法解决

For some reason, the "soma" variable always logs as "NaN" when inside the for loop.出于某种原因,“soma”变量在 for 循环内始终记录为“NaN”。 Prob is something simple, but i've been hitting my head on the desk for almost an hour now. Prob 很简单,但我已经将头撞在桌子上将近一个小时了。 Help D:求助丁:

 const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8] // Luhn Algorithm validateCred = (array) => { var count = 0 var soma = 0 for (i=array.length; i;= -1. i--) { if (count === 0) { count += 1 soma += array[i] } else { if(array[i]*2 > 9) { soma += array[i]*2 - 9 } else { soma += array[i]*2 } count = 0 } console.log(soma%10) // expected output === 0 } } validateCred(valid1)

Change the i=array.length to i=array.length - 1 & move your console.log after loopi=array.length更改为i=array.length - 1并在循环后移动您的 console.log

const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]
// Luhn Algorithm
validateCred = (array) => {
    var count = 0
    var soma = 0
    for (i=array.length - 1; i != -1; i--) {
        if (count === 0) {
            count += 1
            soma += array[i]
        } else {
            if(array[i]*2 > 9) {
                soma += array[i]*2 - 9
            } else {
                soma += array[i]*2
            }
            count = 0
        }
    }
     console.log(soma%10) // expected output === 0
}

validateCred(valid1)

The last item of an array is in the array.length-1 position, since the first element is in the 0 position that's why array[array.length] return nan.Besides you may want to read about the standard methods for iterate over an array: array.foreach(), array.filter(), array.reduce and array.map().数组的最后一项在 array.length-1 position 中,因为第一个元素在 0 position 中,这就是 array[array.length] 返回 nan 的原因。此外,您可能还想阅读有关迭代的标准方法数组:array.foreach()、array.filter()、array.reduce 和 array.map()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM