Parsing the polysemy of the bracket '[]' in Javascript

  • 2020-03-30 00:41:45
  • OfStack

There are four semantics for parentheses in Javascript

Semantics 1, declare an array

var ary = []; //Declare an empty array
var ary = [1,3]; //Declare an array and assign an initial value

Semantics 2, take an array member

var ary = [1,2,3];
var item = ary[0];

Semantics 3, define object members (can not follow identifier rules)

var obj = {};
//Add a property name for obj, and name is a valid identifier, that is, you can also define it in
obj['name'] = 'jack'; 
//Add an attribute 2a for obj, which is not a valid identifier (cannot begin with a number) and cannot be defined by obj.2a
obj['2a'] = 'test'; 

Semantics 4, take object members

var obj = {name:'jack'};
obj['2a'] = 'test';
obj['name']; // --> jack
obj['2a']; //-> Test (not obj.2a)

Related articles: