-1

I am trying to get a dictionary with access to its values by a specific index name. E. g. glyphs["asterisk"] would give "\e201"

Here's my code:

<!DOCTYPE html>
<head><meta charset="utf-8"></head>
<body></body>

 <script>
var glyphNames = ["asterisk","plus","eur","minus","cloud","envelope","pencil","glass","music","search","heart","star","star-empty"]
    
var glyphCodes = [
"\002a", "\002b", "\20ac", "\2212", "\2601", "\2709", "\270f", "\e001", "\e002", "\e003", "\e005", "\e006", "\e007"]
    
var glyphs = []
for(var i=0; i<glyphNames.length; i++) {
   glyphs[glyphNames[i]]=glyphCodes[i]
}
console.log(glyphs)
    
</script>
</html>

But the result is buggy like this asterisk: "\u0002a", cloud: "°1", envelope: "¸9", eur: "\u0010ac", glass: "e001", heart: "e005", minus: "‘2", music: "e002", pencil: "¸f", plus: "\u0002b", search: "e003", star: "e006", star-empty: "e007"

Did anyone try to do this? Any idea why so weird results?

Mottore
  • 17
  • 6
  • I strongly encourage you to move to [JavaScript modules](//developer.mozilla.org/en/docs/Web/JavaScript/Guide/Modules) or at least enable [strict mode](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Strict_mode). Your code throws a SyntaxError in strict mode because you’re using the deprecated [octal escape](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Errors/Deprecated_octal) feature. You are also misusing arrays. Use an [Object initializer](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer) instead. – Sebastian Simon Jan 27 '23 at 01:11

1 Answers1

0

The backslash is a reserved character in Javascript. If you want to escape it so it it is not read as an escape sequence, you need to add another backslash right before:

var glyphCodes = [
"\\002a", "\\002b", "\\20ac", "\\2212", "\\2601", "\\2709", "\\270f", "\\e001", "\\e002", "\\e003", "\\e005", "\\e006", "\\e007"]
  • If I use this notation var glyphCodes = [ "\\002a", "\\002b", I get this result: ["\\002a", "\\002b", etc. - not escaped – Mottore Jan 27 '23 at 11:35