最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery convert integer to string and back - Stack Overflow

programmeradmin2浏览0评论

These are the logical steps which I need to do with jquery:

x is a 2 digit number(integer) derived from an input.value();

If  var x is **not** 33 or 44
    Convert this 2 digit number to string;
    split the string in 2 parts as number;
    Add these 2 values until they reduce to single digit;
    Return var x value as this value;
Else
    Return var x value literally as 33 or 44 whatever is the case;

Thanks!

These are the logical steps which I need to do with jquery:

x is a 2 digit number(integer) derived from an input.value();

If  var x is **not** 33 or 44
    Convert this 2 digit number to string;
    split the string in 2 parts as number;
    Add these 2 values until they reduce to single digit;
    Return var x value as this value;
Else
    Return var x value literally as 33 or 44 whatever is the case;

Thanks!

Share Improve this question edited May 2, 2010 at 4:47 BalusC 1.1m376 gold badges3.7k silver badges3.6k bronze badges asked May 2, 2010 at 4:30 RichbyteRichbyte 511 gold badge1 silver badge2 bronze badges 2
  • Is just Javascript also acceptable? – BalusC Commented May 2, 2010 at 4:35
  • sure but i missed one part: Add these 2 values (until they reduce to single digit); Return var x value as this value. – Richbyte Commented May 2, 2010 at 4:38
Add a ment  | 

2 Answers 2

Reset to default 3
if (x != 33 && x != 44) {
    while (x > 9) {
        var parts = ('' + x).split('');
        x = parseInt(parts[0]) + parseInt(parts[1]);
    }
    return x;
} else {
    return x;
}    

Works only if the input is really max 2 digits long as you say, else you'll need to add the numbers in a for loop over parts.length. E.g.:

if (x != 33 && x != 44) {
    while (x > 9) {
        var parts = ('' + x).split('');
        for (var x = 0, i = 0; i < parts.length; i++) {
            x += parseInt(parts[i]);
        }
    }
    return x;
} else {
    return x;
}    

I'd try:

function process (x) {
    if ((x != 33) && (x != 44)) {
        while (x > 9) {
            x = Math.floor (x / 10) + (x % 10);
        }
    }
    return x;
}

I see little reason to convert it to a string when you can use arithmetic operations.

发布评论

评论列表(0)

  1. 暂无评论