Home  >  Article  >  Web Front-end  >  Parsing the ambiguity of square brackets "[]" in Javascript_javascript skills

Parsing the ambiguity of square brackets "[]" in Javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:11:001071browse

Javascript square brackets have four semantics

Semantics 1, declare array

Copy code The code is as follows:

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

Semantic 2 , take the array members
Copy code The code is as follows:

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

Semantic 3, define object members (you can not follow identifier rules)
Copy code The code is as follows:

var obj = {};

// Add an attribute name to obj. name is a legal identifier, that is, it can also be defined through obj.name
obj['name'] = 'jack';

// Add an attribute 2a to obj. 2a is not a legal identifier (cannot start with a number) and cannot be defined by obj.2a
obj['2a'] = 'test';


Semantics 4, get object members
Copy code The code is as follows:

var obj = {name:'jack'};
obj['2a'] = 'test';

obj['name']; // --> jack
obj['2a']; // --> test (cannot be obtained through obj.2a)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn