๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

ํ”„์—” ๊ณต๋ถ€/๐Ÿซง ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ณต๋ถ€

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/Javascript] ์˜์–ด๊ฐ€ ์‹ซ์–ด์š” || ์ฝ”๋”ฉํ…Œ์ŠคํŠธ

728x90
function solution(numbers) {
    var answer = 0;
    const en = { "zero": 0, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9 };
    const keys = Object.keys(en);
    for (let i = 0; i < keys.length; i++) {
        numbers = numbers.replaceAll(keys[i], en[`${keys[i]}`]);
    }
    return Number(numbers);
}

 

key๋“ค์„ ๋ฐฐ์—ด๋กœ ๋งŒ๋“  ํ›„, ๊ทธ ๋ฐฐ์—ด์˜ ๊ฐ’๋“ค์„ ํ•˜๋‚˜์”ฉ value๋กœ ๋ฐ”๊ฟ”์คฌ๋‹ค.

 

 

 

๋ณ€๊ฒฝํ•˜๋Š” ๋ถ€๋ถ„์„ ์ด๋ ‡๊ฒŒ, replace ์— ๋‘๋ฒˆ์งธ ์ธ์ž๋กœ callback ์„ ๋„ฃ์–ด์„œ ๋ณ€๊ฒฝํ•  ์ˆ˜๋„ ์žˆ๋‹ค.  

์ •๊ทœ์‹ ์•ˆ์— | OR ์„ ๋„ฃ์„ ์ˆ˜ ์žˆ๋Š”๊ฑด ์ฒ˜์Œ ์•Œ์•˜๋‹ค. 

 

    const num = numbers.replace(/zero|one|two|three|four|five|six|seven|eight|nine/g, (v) => {
        return obj[v];
    });

 

728x90
๋ฐ˜์‘ํ˜•