我想要的是:
-> If there are an even number of digits, double every other digit starting with the first
-> If there are an odd number of digits, double every other digit starting with the second.
这是我到目前为止所做的:
function validate(n){
var num = n.toString(); // THIS COULD BE AN ARRAY OR WHATEVER
if (eval(num%2==0)) { // IF HAS EVEN NUMBER OF DIGITS
for (var i=0; i<num.length; i++) {
if (num.charAt(i) === num.charAt(0)) {
eval(num.charAt(i)*=2);
}
}
console.log(num);
} else { // IF HAS ODD NUMBER OF DIGITS
for (var i=0; i<num.length; i++) {
if (num.charAt(i) === num.charAt(1)) {
eval(num.charAt(i)*=2);
}
}
console.log(num);
}
}
validate(1234516178);
示例:
1714 => [1*, 7, 1*, 4] => [2, 7, 2, 4]
891 => [8, 9*, 1] => [8, 18, 1]
希望我很清楚。有人可以帮忙吗?欣赏!
答案 0 :(得分:2)
也许这适合你。它利用带有值的数组并迭代值来改变。
function validate(n) {
var array = n.toString().split('').map(Number),
number = n % 2 ? array[1] : array[0];
return array.map(function (a) {
return a === number ? 2 * a : a;
});
}
function print(o) {
document.write('<pre>' + JSON.stringify(o, 0, 4) + '</pre>');
}
print(validate(1234516178));
print(validate(1714)); // => [1*, 7, 1*, 4] => [2, 7, 2, 4]
print(validate(891)); // => [8, 9*, 1] => [8, 18, 1]
答案 1 :(得分:0)
您可以尝试这样的事情:
function validate(n) {
n = n.toString();
var isEven = (parseInt(n, 10) % 2 === 0);
var digits = n.split("");
// Strings to numbers
digits.forEach(function(digit, index) {
digits[index] = parseInt(digit, 10);
});
if(isEven) {
var firstDigit = digits[0];
digits.forEach(function(digit, index) {
console.log(digit);
if(digit === firstDigit) {
digits[index] *= 2;
}
});
} else {
var secondDigit = digits[1];
digits.forEach(function(digit, index) {
if(digit === secondDigit) {
digits[index] *= 2;
}
});
}
return JSON.stringify(digits);
}
当然,包括更多条件并只留下一个forEach
可以做得更好答案 2 :(得分:0)
你不需要字符串来做那件事
function validate(s){
var a = parseInt(s);
var b = 0;
var odd = (a+'').length %2//true;
//var summ = 0;
while(a>=1){
var b = Math.floor(a%10);
var c = odd?b: b*2//<10? b*2 : b*2-9;
//summ += c;
odd = !odd;
a = a/10;
//output
$('input').after('+'+c)
}
//output
$('input').after('<br>')//.after(summ).after('<br> summ: ')
//return summ%10
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="validate($('input').val())">validate</button>
<input>
&#13;