我从昨天开始就在寻找这个,已经搜索了很多,但没有找到我所需要的任何答案。如果您发现任何问题,请告诉我,我将不胜感激并关闭此问题:)
我想要的是:
-> 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]
希望我说得清楚。有人可以帮忙吗?欣赏!
最佳答案
也许这对你有用。它使用包含值的数组并迭代要更改的值。
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]
关于javascript - 如何计算字符串中的某些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34676807/