Javascript中的复合赋值导致NaN

时间:2013-07-24 13:15:14

标签: javascript

我正在尝试让复合赋值在Javascript循环中工作,但它正在向我抛出NaN,我不知道为什么因为我仍然是Javascript的新手。我基本上试图将其转换为jQuery-Validation自定义方法:https://github.com/pfwd/NHSNumber-Validation/blob/master/PHP/NHSValidation.class.php

这是我到目前为止所拥有的

        // Taken from https://github.com/pfwd/NHSNumber-Validation
        var multipliers = {1:10, 2:9, 3:8, 4:7, 5:6, 6:5, 7:4, 8:3, 9:2};
        var currentSum, currentNumber, currentMultiplier = 0;

        //Get submitted NHS Number and remove whitespace
        var givenNumber = value.replace(/\s+/g, '');

        // Get length
        var numberLength = givenNumber.length;
        console.debug(givenNumber);
        console.debug(numberLength);

        // Number must be 10 digits in length
        if (numberLength !== 10) {
            return false;
        }

        // Check number
        var checkNumber = value.substring(9);
        console.debug(checkNumber);

        // Loop over each number in the string and calculate the current sum
        for (var i = 0; i <= 8; i++) {
            var minus = i-1;
            var plus = i+1;
            currentNumber = value.charAt(i);
            currentMultiplier = multipliers[plus];
            currentSum += (currentNumber * currentMultiplier);
            console.debug("i is " + i + " & current Num: " + currentNumber + " plus current multi: " + currentMultiplier + " plus " + currentSum);
        }

        var remainder = currentSum % 11;
        var total = 11 - remainder;
        console.debug(currentSum);

我不知道减号和正号是否是必要的,但我们尝试解决NaN问题时尝试了这些。典型的控制台调试行如下所示:

i is 0 & current Num: 1 plus current multi: 10 plus NaN 

我也尝试了同样的NaN结果:

currentSum = currentSum + (currentNumber * currentMultiplier);

1 个答案:

答案 0 :(得分:1)

var currentSum, currentNumber, currentMultiplier = 0;

不正确,只初始化当前的乘数。

应该是

var currentSum, currentNumber, currentMultiplier;
currentSum =  currentNumber = currentMultiplier = 0;

演示:http://jsfiddle.net/46dD5/