The ambiguity of brackets "[]" in Javascript
This article mainly introduces the ambiguity of the brackets "[]" in Javascript. For more information, see.
Javascript Brackets have four Semantics
Syntax 1: declare an array
The Code is as follows:
Var ary = []; // declare an empty array
Var ary = [1, 3]; // declare an array and assign the Initial Value
Semantics 2: retrieve array members
The Code is as follows:
Var ary = [1, 2, 3];
Var item = ary [0];
Semantics 3: Define object members (you can not follow the identifier rules)
The Code is as follows:
Var obj = {};
// Add an attribute name for obj. name is a valid identifier, which can be defined by obj. name.
Obj ['name'] = 'jack ';
// Add an attribute 2a for obj. 2a is not a legal identifier (cannot begin with a number) and cannot be defined through obj.2a
Obj ['2a '] = 'test ';
Semantics 4: Get object members
The Code is as follows:
Var obj = {name: 'jack '};
Obj ['2a '] = 'test ';
Obj ['name']; // --> jack
Obj ['2a ']; // --> test (cannot be obtained through obj.2a)