使用JavaScript编码morsecode

4 javascript

我试图以最简单的方式将任何文本字符串转换为摩尔斯电码.我对编程很新,所以请你给我一些关于我可以用什么方法的建议.

到目前为止,我刚刚编写了一个短语(字符串)和一个包含摩尔斯电码的数组,但我正在努力解决下一步如何使用字符串的每个字符,然后使用数组检查它并打印出摩尔斯电码相当于的字符串.

var phrase = "go down like a lead balloon";

var morseCode = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-",     ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]

for(i=0; i<phrase.length; i++){

c = phrase.charAt(i);

WScript.echo(c + " | " + i);
}  
Run Code Online (Sandbox Code Playgroud)

Cer*_*rus 10

您可以使用字典,如下所示:

var alphabet = {
    'a': '.-',    'b': '-...',  'c': '-.-.', 'd': '-..',
    'e': '.',     'f': '..-.',  'g': '--.',  'h': '....',
    'i': '..',    'j': '.---',  'k': '-.-',  'l': '.-..',
    'm': '--',    'n': '-.',    'o': '---',  'p': '.--.',
    'q': '--.-',  'r': '.-.',   's': '...',  't': '-',
    'u': '..-',   'v': '...-',  'w': '.--',  'x': '-..-',
    'y': '-.--',  'z': '--..',  ' ': '/',
    '1': '.----', '2': '..---', '3': '...--', '4': '....-', 
    '5': '.....', '6': '-....', '7': '--...', '8': '---..', 
    '9': '----.', '0': '-----', 
}

"This is a sentence containing numbers: 1 2 3 4 5"
    .split('')            // Transform the string into an array: ['T', 'h', 'i', 's'...
    .map(function(e){     // Replace each character with a morse "letter"
        return alphabet[e.toLowerCase()] || ''; // Lowercase only, ignore unknown characters.
    })
    .join(' ')            // Convert the array back to a string.
    .replace(/ +/g, ' '); // Replace double spaces that may occur when unknow characters were in the source string.

// "- .... .. ... / .. ... / .- / ... . -. - . -. -.-. . / -.-. --- -. - .- .. -. .. -. --. / -. ..- -- -... . .-. ... / .---- / ..--- / ...-- / ....- / ....."
Run Code Online (Sandbox Code Playgroud)

  • "气味"是一个闻起来的短语?XD (2认同)