Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

字符串转数字 #259

Open
Sunny-117 opened this issue Nov 4, 2022 · 2 comments
Open

字符串转数字 #259

Sunny-117 opened this issue Nov 4, 2022 · 2 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@bearki99
Copy link

// 如果不是大数的情况
// 1. parseInt
let str = '123';
let res = parseInt(str);
// 2. +
let res1 = +str;
// 3. ~~
let res2 = ~~str;
// 4. Number
let res3 = Number(str);


// 如果是大数的情况
let res4 = BigInt(str);

@veneno-o
Copy link
Contributor

  • 类似于parseInt的底层实现
function transfrom(str){
    let sum = 0;
    for(let i = 0; i < str.length; ++i){
        const value = str.charAt(i);
        if(value < "0" || value > "9") break;
        sum *= 10;
        sum += strToNumber(value);
    }
    function strToNumber(char){
        switch (char) {
            case "1":
                return 1
            case "2":
                return 2
            case "3":
                return 3
            case "4":
                return 4
            case "5":
                return 5
            case "6":
                return 6
            case "7":
                return 7
            case "8":
                return 8
            case "9":
                return 9
            default:
                return 0
        }
    }
    return sum;
}

console.log(transfrom("12314sadfa"))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants