在for循环中生成unicode字符列表 [英] Generate a list of unicode characters in a for loop

查看:265
本文介绍了在for循环中生成unicode字符列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图列出一个for循环中的计数器作为unicode字符的数量。这样做的目的就是让我说出我在玩的乐趣。当然,一个经验丰富的javascript用户可以告诉我这里有什么问题。

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.

要在javascript中使用unicode字符,可以直接键入它,或者使用转义序列,如: \\\舑 。我的问题出现在我尝试将数字组合与转义的u组合时。我得到的错误是不好的转义字符,这意味着 i 变量中的数字不与\
(我希望的)。

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'));
}

我尝试过:

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

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

...我用完了想法

一个例子:

jsfiddle.net/Dn4Vv /

推荐答案

最大的问题是 \uXXXX 当代码被解析时被解释;就像你不能写'''''''''表示与相同(因为是代码中的实际双引号,而''是一个包含 ),你不能写'\\u'+'XXXX'表示相同作为'\uXXXX'

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'.

正如Brad Christie在上述评论中所说,你应该使用函数 String.fromCharCode 将整数转换为您需要的字符:

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);

第二个问题,这是学术性的,由于上述原因,但我想我应该提到它是 \uXXXX 符号期望字符代码以十六进制符号表示,并零填充到正好四个十六进制数字,而您以十进制表示法,而不填补。例如,您正在写 \u65 ,但 A 的Unicode转义语法实际上是 \\\A

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.

这篇关于在for循环中生成unicode字符列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆