2

I know there's no "dictionary" in Javascript. So the key can be "more than a string" . But how to explain the result "[index] = index"?

a={["abc"]:123}
a["abc"]==123
true

Why it works?

I've update the statement above. Sorry for misunderstanding.

fxp
  • 6,792
  • 5
  • 34
  • 45
  • 1
    Your code does not work. What are you trying to ask? – Xatenev Jun 01 '17 at 11:29
  • 1
    @Barmar It doesn't do that. What version of ES are we talking about anyway? This will result in a SyntaxError. – Xatenev Jun 01 '17 at 11:30
  • @Xatenev I think OP is trying to say that if you have `obj = {"abc":123}`, you can access `obj[["abc"]]` (note extra brackets) and it "works". That's indeed because the array gets converted to a string. – Niet the Dark Absol Jun 01 '17 at 11:31
  • @NiettheDarkAbsol That would make sense. Thanks for explaining. I thought OP tried to execute his **exact** JS code here and it worked. – Xatenev Jun 01 '17 at 11:34
  • Your code does not work: See this fiddle: https://codepen.io/HPawelyn/pen/BZBoVa?editors=1111 – H. Pauwelyn Jun 01 '17 at 11:34
  • 2
    I don't think hemeant that as an assignment, he means that the two syntaxes are equivalent. – Barmar Jun 01 '17 at 11:35
  • @NiettheDarkAbsol Thanks for explaining for me. – fxp Jun 01 '17 at 11:36
  • I'm trying to explain that {["abc"]:123} result in a object "looks like the same with" {"abc":123} . Sorry for my poor statement @Barmar – fxp Jun 01 '17 at 11:37
  • @fxp I understood it, H.Pauwelyn didn't. – Barmar Jun 01 '17 at 11:38
  • Why do you think the key can be more than a string? – Barmar Jun 01 '17 at 11:39
  • @Barmar at least number can be key as well – fxp Jun 01 '17 at 11:46
  • @fxp The number gets converted to a string. Try `Object.keys([1, 2, 3])` – Barmar Jun 01 '17 at 11:48
  • try this a[1e2] =23; a['1e2'] @Barmar – fxp Jun 01 '17 at 11:51
  • `1e2` is `100`, so the first is `a['100'] = 23` – Barmar Jun 01 '17 at 11:52
  • @Barmar You are right. And the Object.keys(a) is also ["100"]. So you mean that the key can be only string? I find another question https://stackoverflow.com/questions/6066846/keys-in-javascript-objects-can-only-be-strings which says a[1] is actually converted to a["1"]. And I find another reference about Symbol https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols that means key can be Symbol for now? – fxp Jun 01 '17 at 12:02

2 Answers2

6

In new es6 you can use this [] to compute dynamic keys.

var a = {
  [2 * 3]: "what"
}
console.log(a);
Barmar
  • 741,623
  • 53
  • 500
  • 612
Anurag Awasthi
  • 6,115
  • 2
  • 18
  • 32
1

It's ES6 Computed property name syntax:

{ [expression]: value }

In your case expression is just a string "abc".

Alexey Ten
  • 13,794
  • 6
  • 44
  • 54