我有一个程序,将二进制/莫尔斯码/十六进制转换为ASCII,但由于某种原因,输出到dom显示方形。我猜这是因为它不知道如何解释这些字符。
我不知道如何让javascript显示正确的字符。在控制台中,它给出了正确的响应,但是当我将它发送到DOM时,它显示了那些可怕的框。
首先,我想知道为什么控制台显示正确的输出,但DOM没有,其次,我如何让DOM显示正确的输出。
我尝试将HTML编码更改为UTF-16,但这不起作用。我在用chrome浏览器。下面是程序的一小段
if (baseButton.textContent == "morse") {
const get = await fetch("morse.json") //this gets the morse from a JSON file
const morseData = await get.json()
const keys = Object.keys(morseData);
const values = Object.values(morseData);
let morseArray = secretMessage.split(' ') // this is the morse/binary/hex... from an input in html
let string = ''
for (let i = 0; i < morseArray.length; i++) {
for (let j = 0; j < keys.length; j++) {
if (morseArray[i] == values[j]) string += keys[j]
}
}
console.log(string) //this gives the correct output in the console
output.textContent = string.replace(/ /g, " ") // this shows boxes in the DOM
} // output is displayed in the HTML below
<div id="result">
<span>result:</span>
<p>
<pre id="code"></pre>
</p>
</div>
从你展示的代码中我看不出来——我们需要看到你的对象,二进制文件可能没有经过字符串化
但是对于morse,这更简单-我使用_作为空格
const secretMessage = ".... . .-.. .-.. --- _ .-- --- .-. .-.. -..";
const a2morse = {"_": "_", "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":"--.."};
const morse2a = Object.keys(a2morse).reduce((acc,cur) => {
acc[a2morse[cur]] = cur
return acc
},{})
let str = secretMessage.split(" ").map(l => `${morse2a[l]}`).join("")
console.log(str) //this gives the correct output in the console
document.getElementById('output').textContent = str
<pre id="output"></pre>