iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 24
0
Modern Web

從Stack Overflow學前端系列 第 24

從StackOverflow上學CODING(24)為何 ◎ܫ◎或 ☺不能成為一個 JS變數名

Why aren't ◎ܫ◎ and ☺ valid JavaScript variable names?

I noticed that in Internet Explorer (but, unfortunately, not in the other browsers I tested), you can use some Unicode variable names. This made my day, and I was absolutely delighted that I could write fun Unicode-laden code like this:

我注意到在IE(其他瀏覽器則沒有),你可以用一些有Unicode的變數名字,我還滿高興可以在變數上取一些有趣的名字像是:

var ктоείναι草泥马 = "You dirty horse.",
    happy☺n☺mat☺p☺eia = ":)Yay!",
    ಠ_ಠ = "emoticon";

alert(ктоείναι草泥马 + happy☺n☺mat☺p☺eia + ಠ_ಠ);

For some reason, though, ◎ܫ◎, ♨_♨ and ☺ are not valid variable names.

Why do ಠ_ಠ and 草泥马 work, but ◎ܫ◎, ♨_♨ and ☺ don't?

EDIT: Test it out in your browser on JSFiddle. I've tested it in Internet Explorer 9, Chrome, Firefox, and Opera. So far, it seems to only work in Internet Explorer 9. (I don't know about Internet Explorer 8 and below.) Let me know if it works in another browser.

但是出於某些原因,◎ܫ◎, ♨♨ 和 ☺則不是有效的變數名,這是為甚麼呢?
在你的瀏覽器和JSFiddle試試看,我有在IE9、chrome、firefox和opera上面試過,到目前為止,好像只有在IE9上才能這樣做(IE8以下我沒試過)如果可以在其他瀏覽器上用的話請讓我知道


ಠ_ಠ and 草泥马 only contain "letters" used in actual alphabets; that is, ಠ is a symbol from the Kannada alphabet, and 草泥马 consists of Chinese characters.
ಠ_ಠ 和 草泥马 只是"字體"存在於在字母表內,ಠ是一個在Kannada字母表,而草泥马則存在於中文字體中

◎ and ☺, however, are purely symbols; they are not associated with any alphabet.
然而, ◎ 和 ☺ 則是純粹的符號,他們跟任何字母表都沒有關連

The ECMAScript standard, chapter 7.6 (which all the browsers except Internet Explorer are following), states that an identifier must start with one of the following.
在ECMAScript標準內,有聲明過一個識別碼必須開頭為任一以下列:

a Unicode letter
$ or _
\ followed by a unicode escape sequence.

一個 Unicode字體
$或 _
\

The following characters of an identifier must be one of the following.
any of the characters permitted at the start:
任何開頭為以下列的識別碼:

a Unicode combining mark
a Unicode digit
a Unicode connector punctuation
a zero-width-non-joiner
a zero-width joiner

IE goes beyond the standard and is permissive enough to allow some symbols, such as ☺.
IE則超越了標準、更加寬容的允許更多符號像是 ☺

There’s a tool that will tell you if any string that you enter is a valid JavaScript variable name according to ECMAScript 5.1 and Unicode 6.1.
有一個工具可以告訴你你的字串能不能設為一個 JavaScript變數名根據 ECMAScript 5.1 和 Unicode 6.1


上一篇
從StackOverflow上學CODING(23) 如何用 JS刪除所有 CSS Class
下一篇
從StackOverflow上學CODING(25) 甚麼時候用 call()& apply()& bind()
系列文
從Stack Overflow學前端30

尚未有邦友留言

立即登入留言