这是一个将给定句子加密为国际莫尔斯电码的函数,输入和输出都将是字符串。字符之间用一个空格分隔。单词之间用三个空格隔开。例如,"HELLO WORLD"应该返回 -> ".... . .-.. .-..--- -- --- .-- -…-.."
提供了一个名为CHAR_TO_MORSE的预加载对象/字典/散列来帮助将字符转换为摩尔斯电码。
然而,我不明白为什么我们需要一个内循环的函数?
function encryption(message) {
var arr = message.split(" "); //I understand here we split the string into individual words
for(var i = 0; i < arr.length; i++) {
arr[i] = arr[i].split(""); //then we use the loop to split the words further into characters?
for(var j = 0; j < arr[i].length; j++) { //but we need an inner loop here? what is the purpose of this j loop? is that necessary ?
arr[i][j] = CHAR_TO_MORSE[arr[i][j]]; //can’t we just use arr[i] CHAR_TO_MORSE[arr[i]]...I think I totally lost the logic here...
}
arr[i] = arr[i].join(" ");
}
arr = arr.join(" ");
return arr;
}
也,如果这个解决方案不是最优的,请提出一个更好的方案。
你有一个句子。你把它变成一个单词数组。你把每个单词变成一个字符数组。现在你有了一个字符数组的数组。
两个循环就可以了。循环遍历每个单词,内部循环遍历每个字符。
你仍然只"击中"每个字符一次,所以没有"重复"。
还有其他方法可以解决这个问题,你可以在原始代码中循环遍历每个字符,而不使用split。我不确定制作这些数组是否有很大的优势——但这并不是"错误的"。