短い答え
オブジェクトのプロパティ名は、(空の文字列を含む)任意のvalid identifier、numeric literal、またはstring literalことができます。
これで、JavaScriptのプロパティ名について覚えておかなければならない複雑なことがいくつかあります(要約は下記にあり、explored more on my own)。
負の数負の数は、実際の式であるように見えるかもしれません何
- プロパティ名はサポートしていません何か。
var obj = {
-12: 'nope' // I am an invalid property name, because I am an expression.
};
幸いにも、ブラケット表記は私たちの表現を処理します。
obj[-6] = 'yup'; // Successful property assignment. We're good here.
解析&型キャストは
すべてのプロパティ名が格納される前に文字列に型変換されています。
var obj = {
lego: 'Everything is cool when you\'re part of a string.'
};
for (var key in obj) console.log(key); // "lego"
しかし、それ以前でさえ、使用されている構文に従って構文解析され、10進リテラルに変換されます。
var objValid = {
'022': 'alligator', // valid string literal
6: 'cow', // interpreted as decimal, evaluates to 6
.345: 'bear', // interpreted as floating-point; evaluates to 0.345
1.000: 'fox', // interpreted as floating-point, evaluates to 1
8.9890: 'owl', // interpreted as floating-point, evaluates to 8.989
000888: 'fish', // interpreted as decimal, evaluates to 888
0777: 'monkey', // interpreted as octal, evaluates to 511
0x00111: 'elephant', // interpreted as hexadecimal, evaluates to 273
0b0011: 'donkey', // interpreted as binary, evaluates to 3
};
console.log(objValid['022']); // "alligator"; as expected
console.log(objValid[022]); // undefined; 022 is an octal literal that evaluates to 18 before our lookup ever occurs
console.log(objValid[6]); // "cow"; as expected
console.log(objValid['6']); // "cow"; as expected
console.log(objValid[0777]); // "monkey"; we're accessing the property name as it was assigned (before it was parsed and typecasted)
console.log(objValid['0777']); // undefined; after parsing and typecasting, our property name seems to have disappeared
console.log(objValid['511']); // "monkey"; there it is, we found it using the evaluation of our original assignment
console.log(objValid[0x00111]); // "elephant"; we're accessing the property name as it was assigned (before it was parsed and typecasted)
console.log(objValid['0x00111']); // undefined; after parsing and typecasting, our property name seems to have disappeared
console.log(objValid['273']); // "elephant"; there it is, we found it using the evaluation of our original assignment
console.log(objValid[0b0011]); // "donkey"; we're accessing the property name as it was assigned (before it was parsed and typecasted)
console.log(objValid['0b0011']); // undefined; after parsing and typecasting, our property name seems to have disappeared
console.log(objValid['3']); // "donkey"; there it is, we found it using the evaluation of our original assignment
結論
あなたは、有効な(non-negative integer)配列インデックスで作業している場合を除き - 明示的に文字列として全ての数値プロパティ名を割り当てます。第一の質問には
なぜ7が有効な識別子ではありません。ここで
は、いくつかの興味深い記事がありますか? – MinusFour
@MinusFour: 'var 7 = 9;'は構文エラーです。 –
そして私たちをさらに狂わせるために、プロパティ名として8進数を使うことができます: 'var x = {7:" a "、x010:" b "}; ' –