简体   繁体   English

javascript unicode 与 html 连接

[英]javascript unicode connection with html

I have a program that converts binary/morse/hex to ASCII but for some reason the output to the dom shows squares.我有一个将二进制/莫尔斯/十六进制转换为 ASCII 的程序,但由于某种原因 output 到 dom 显示正方形。 I'm assuming it's because it doesn't know how to interpret the characters.我假设这是因为它不知道如何解释字符。

I don't know how to get javascript to show the right characters.我不知道如何让 javascript 显示正确的字符。 In the console it gives the correct response but as soon as I send it to the DOM it shows those dreaded boxes.在控制台中,它给出了正确的响应,但是一旦我将它发送到 DOM,它就会显示那些可怕的框。

Firstly I would like to know why the console is showing the correct output but the DOM doesn't, and secondly how to I get the DOM to show the correct output.首先,我想知道为什么控制台显示正确的 output 但 DOM 没有,其次如何让 DOM 显示正确的 output。

I tried changing the HTML encoding to UTF-16 but that didn't work.我尝试将 HTML 编码更改为 UTF-16,但这没有用。 I'm using chrome.我正在使用铬。 here is a small piece of the program这是程序的一小部分

 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>

I cannot tell from the code you show - we need to see your object, The binary likely isn't stringified我无法从您显示的代码中看出 - 我们需要查看您的 object,二进制文件可能没有被字符串化

But for morse this is simpler - I used _ as space但对于 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM