Generate a list of unicode characters in a for loo

2019-06-22 08:58发布

问题:

I am trying to list use the counter in a for loop as the number of a unicode character. The purpose of this, ...lets just say I am doing it for fun. Surely, a seasoned javascript user will be able to tell me what is wrong here.

To use a unicode character in javascript one can either type it in as it is, or use an escape sequence like: \u8211. My problem arises when I try to combine the number part with the escaped u. The error I get is something along the lines of "bad escape character", and it means that the number from the i variable is not combined with the \u as I'm hoping for.

for (var i=65; i< 90; i++ ) {                                          
    anchor = document.createElement('a'),
    img = document.createElement('img'),
    character = "\\u"+i;
    img.setAttribute('alt', character);
    img.setAttribute('src', '');

    anchor.appendChild(document.createTextNode(i +": "));
    anchor.appendChild(img);

    anchor.setAttribute('title', character);
    body.appendChild(anchor);
    body.appendChild(document.createElement('br'));
}

What I have tried:

character = "\u{"+i+"}"

cha = ['\\u'];
cha.push(i);
cha.join('');

... and i've run out of ideas

An example:

jsfiddle.net/Dn4Vv/

回答1:

The biggest problem is that \uXXXX is interpreted at the time that the code is parsed; just as you can't write '"' + '"' to mean the same as "" (because " is an actual double-quote in the code, whereas '"' is a string containing "), you can't write '\\u' + 'XXXX' to mean the same as '\uXXXX'.

As Brad Christie says in a comment above, you should use the function String.fromCharCode to convert from an integer to the character you need:

    character = String.fromCharCode(i);

A second problem — this is academic, due to the above, but I think I should mention it — is that the \uXXXX notation expects the character code to be given in hexadecimal notation, and zero-padded to exactly four hexadecimal digits, whereas you're giving it in decimal notation, and without zero-padding. For example, you're writing \u65, but the Unicode-escape syntax for A is actually \u0041.



回答2:

Try this: String.fromCharCode(i);.



回答3:

character = String.fromCharCode(i); // works for me


回答4:

Try something like this:

<script language=Javascript>
charCode=2665;
uc='"\\u' + charCode +'"';
document.write('<a title="' + charCode + '">' + eval(uc) + '</a>');
</script>