当用户添加到表单时,我需要验证促销代码是否有效。 1.必须有9个字符 2.将第一个数字乘以9,第二个数字乘以8,第三个数字乘以7,因此结果数应被11整除 3.一位数字彼此相邻出现的次数不得超过两次
这是我到目前为止所拥有的。
let number = ['613884922'];
let sum = 0
strNumber = number.toString();
if (strNumber.length != 9) {
return false;
}
for (var i = 0; length = strNumber.length; i < 9, i += 1) {
var n = strNumber.charAt(i);
sum += n * (length - i);
}
if (sum % 11 != 0) {
return false;
}
我不确定我做对了吗。
我还需要将其添加到表单中,以便用户可以添加代码并查看他/她是否获胜
我不确定如何将代码添加到表单中。 这是我到目前为止所拥有的。
</head>
<body>
<div class = user>
<h1> Hello! </h1>
<h1> check if you are lucky!</h1>
</div>
<form>
<input name="name" placeholder="What is your name?" class="name" required />
<input name="emailaddress" placeholder="What is your email?" class="email" type="email" required />
<input name="code" placeholder="Add you code here and good luck!" class="code" type="code" required></input>
<input name="submit" class="btn" type="submit" value="Send" />
</form>
<script>
let number = [];
let sum = 0
strNumber = number.toString();
if (strNumber.length != 9) {
return false;
}
for (var i = 0; length = strNumber.length; i < 9, i += 1) {
var n = strNumber.charAt(i);
sum += n * (length - i);
}
if (sum % 11 != 0) {
return false;
}
</script>
</body>
</html>
非常感谢
答案 0 :(得分:1)
函数check
11
的不安分的结果。
function check(string) {
if (string.length !== 9) return 'wrong length';
if (/(\d)\1{2}/.test(string)) return 'too much of the same';
var sum = Array.from(number).reduce((s, v, i) => s + (9 - i) * v, 0);
return !(sum % 11);
}
var number = '613884922',
sum = Array.from(number).reduce((s, v, i) => s + (9 - i) * v, 0);
console.log(check('613884922'));
console.log(check('613384922'));
console.log(check('2'));
console.log(check('2123456789'));
console.log(check('618884922'));