我正在为Javascript中的信用卡号码编写验证程序。我希望它能够检查LUHN变量,并且我想自己编写这些步骤,并且我尝试在for循环的帮助下做到这一点,以便练习它们。 但是,我卡住了,我可以使用一些友好的建议,在这里做什么。 我也对for循环的整个语法有些困惑,所以如何改进它们的提示是值得欢迎的。Javascript,验证,for-loops
该项目是在这里: http://jsfiddle.net/tomasantonj/eZKMa/12/
这里是我遇到的麻烦的代码:
else if (filter.test(cardnumber.value))
{
// 1. Begin with second to last number iterate, every second number with 2 until start.
for(i = 0; i < cardnumber.length;i += 1){
newnumbers = (i * 2);
// 2. The result of the previous string to be added i+i+i.
for (i = 0; i < newnumbers.length; i += 1){
sum1 = (i + i);
// 3. Then add the remaining numbers together but skip the last which is a control number.
for (i = 0; i < cardnumber.length; i += 1){
sum2 = (i + i);
// 4. Add sum1 and sum2 together
var checksum = (sum1 + sum2);
alert('the sum of x and y is: ' + checksum);
// 5. Mod10 out of the checksum + cardnumber control number to get validity.
if ((checksum + cardnumber[-0]) % 10 === 0){
alert('LUHN checks out!');
}
else {
alert('not yet');
}
}
}
}
我不确定如何提出正确的问题,但我猜我的问题是变量范围,for循环和获取for循环来执行基于索引的查询。我知道这段代码很丑,很长,这是我第二次尝试JavaScript,所以请不要太在意。
运行此代码时,校验和未定义 - 任何人都知道这是为什么?可能与字符串和整数有关? :S
任何回应非常感谢。 谢谢, Tomas
如果你可以使用jQuery有一个优秀的信用卡验证插件,检查卢恩校验和以及确定卡的类型:https://github.com/PawelDecowski/jQuery-CreditCardValidator – 2012-04-18 11:14:03
啊,我不能,这是我得到一个学校项目的任务,它应该是JavaScript。没有图书馆等,但谢谢! – tomasantonj 2012-04-18 11:16:07