Javascript Jquery 将整数转换为字符串并返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2752452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:45:51  来源:igfitidea点击:

Jquery convert integer to string and back

javascriptjquerystringnumbers

提问by Richbyte

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

这些是我需要用 jquery 做的逻辑步骤:

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

x是从 input.value() 派生的 2 位数字(整数);

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!

谢谢!

回答by BalusC

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 forloop over parts.length. E.g.:

仅当输入真的像您说的那样最长为 2 位数时才有效,否则您需要在for循环中添加数字parts.length。例如:

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;
}    

回答by paxdiablo

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.

当您可以使用算术运算时,我认为没有理由将其转换为字符串。