简体   繁体   中英

Javascript: Square brackets after function call

I just spent about 15 minutes debugging a piece of Javascript code, and discovered the problem was that I had written

matches.push[[-1]];

instead of

matches.push([[-1]]);

like I intended, where matches is an array. Can somebody explain to me why Javascript didn't throw a syntax error on the former, and what its meaning is?

Why

matches.push is a Function Object , and you can access object properties and methods through dot notation or the bracket notation. Basically you're asking for something which isn't in the push Function Object , so it yields undefined .

在此输入图像描述

Note

If you added something with the key [-1] as in matches[[-1]] = "something" it would also be valid, so the syntax is valid, simply not what you wanted to do.

Its just a property accessor :

 var matches = []; matches.push[1] = 'bla' document.write(matches.push[1]); 

Basically you do the following:

matches.push[[-1]]; 

resolves to (a single number in brackets becomes a string ) and while the accessor for objects is a string , you get

matches.push['-1']

and that resolves to

undefined

because the property '-1' is undefined.

Everything in js is an object, even a function. I imagine the engine just referenced a (nonexistent) field to the push function/object. That results in undefined .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM