简体   繁体   English

Javascript:函数调用后的方括号

[英]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 我花了大约15分钟调试一段Javascript代码,发现问题是我写的

matches.push[[-1]];

instead of 代替

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

like I intended, where matches is an array. 像我的意图, matches是一个数组。 Can somebody explain to me why Javascript didn't throw a syntax error on the former, and what its meaning is? 有人可以向我解释为什么Javascript没有在前者上抛出语法错误,它的含义是什么?

Why 为什么

matches.push is a Function Object , and you can access object properties and methods through dot notation or the bracket notation. matches.push是一个Function Object ,您可以通过点表示法或括号表示法访问对象属性和方法。 Basically you're asking for something which isn't in the push Function Object , so it yields undefined . 基本上你要求的东西不是push Function Object ,所以它产生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. 如果您添加了关键的东西[-1]matches[[-1]] = "something"这也将是有效的,所以语法有效的,你想做的事根本就没有什么。

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. 因为属性'-1'未定义。

Everything in js is an object, even a function. js中的所有东西都是一个对象,甚至是一个函数。 I imagine the engine just referenced a (nonexistent) field to the push function/object. 我想引擎刚刚将一个(不存在的)字段引用到push函数/对象。 That results in undefined . 这导致undefined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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