transliterating cyrillic to latin with javascript function

后端 未结 6 1499
情话喂你
情话喂你 2020-12-28 08:27

I made this function:

function transliterate(word){

    var answer = \"\";

    A = new Array();
    A[\"Ё\"]=\"YO\";A[\"Й\"]=\"I\";A[\"Ц\"]=\"TS\";A[\"У\"         


        
6条回答
  •  余生分开走
    2020-12-28 08:50

    Your primary problem is that the return is in the wrong place. It's inside your loop, so it returns on the first iteration. Change it to:

    function transliterate(word){
    
        var answer = "";
    
        A = new Array();
        A["Ё"]="YO";A["Й"]="I";A["Ц"]="TS";A["У"]="U";A["К"]="K";A["Е"]="E";A["Н"]="N";A["Г"]="G";A["Ш"]="SH";A["Щ"]="SCH";A["З"]="Z";A["Х"]="H";A["Ъ"]="'";
        A["ё"]="yo";A["й"]="i";A["ц"]="ts";A["у"]="u";A["к"]="k";A["е"]="e";A["н"]="n";A["г"]="g";A["ш"]="sh";A["щ"]="sch";A["з"]="z";A["х"]="h";A["ъ"]="'";
        A["Ф"]="F";A["Ы"]="I";A["В"]="V";A["А"]="A";A["П"]="P";A["Р"]="R";A["О"]="O";A["Л"]="L";A["Д"]="D";A["Ж"]="ZH";A["Э"]="E";
        A["ф"]="f";A["ы"]="i";A["в"]="v";A["а"]="a";A["п"]="p";A["р"]="r";A["о"]="o";A["л"]="l";A["д"]="d";A["ж"]="zh";A["э"]="e";
        A["Я"]="YA";A["Ч"]="CH";A["С"]="S";A["М"]="M";A["И"]="I";A["Т"]="T";A["Ь"]="'";A["Б"]="B";A["Ю"]="YU";
        A["я"]="ya";A["ч"]="ch";A["с"]="s";A["м"]="m";A["и"]="i";A["т"]="t";A["ь"]="'";A["б"]="b";A["ю"]="yu";
    
        for (i in word){
    
            if (A[word[i]] === 'undefined'){
                answer += word[i];
                }
            else {
                answer += A[word[i]];
                }
    
        }
        return answer; // <=== Was *above* the } on the previous line
    }
    

    Note that I've fixed the indentation. Consistent indentation helps you avoid these sorts of bugs.


    Note 1: There's nothing about your A object that uses the fact it's an Array. You're just using it as a map. In JavaScript, all objects are maps, so rather than A = new Array(); just use A = {};.

    Note 2: A and i are never declared in your function, so you're falling prey to The Horror of Implicit Globals. To fix it, declare them with var.

    Note 3: Neither using for..in to loop through the characters of a string, nor using [] to index into the string, is reliable across JavaScript engines. Instead, use for (i = 0; i < word.length; ++i) and then ch = word.charAt(i); to get the character at that position, then use ch in your code within the loop.

    Note 4: You can use the Curiously powerful || operator to shorten your code, e.g.:

    answer += A[ch] || ch;
    

提交回复
热议问题