6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptのオブジェクトのキーに配列が使える

Last updated at Posted at 2014-03-12

オブジェクトのキーに配列を使う

var a = {};
a[['key']] = 1;
a[['key']]; //1が取れる

オブジェクトリテラル中でキーに配列を使うと構文エラー

var a = {['key'], 1};

種明かし

配列が文字列化されてキーになっています。

['key']を文字列化すると "key" になります。

String(['key']) // "key"が返る

実際はkeyプロパティが設定されています。

var a = {};
a[['key']] = 1;
a.key; //1が取れる

仕様確認

Working with Objects - JavaScript | MDN

オブジェクトプロパティの名前には、正しい JavaScript 文字列か、空文字列を含む、文字列に変換できるあらゆるものを使えます。

6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?