简体   繁体   中英

JavaScript array `push` with square brackets instead of parentheses - no error?

I did this by accident...

var numbers = [1, 2, 3, 4];
numbers.push[5];

Why wasn't there an error message?

push needs parentheses, not square brackets. It was just a simple typo. I wasn't paying close enough attention to what I was doing... but why wasn't there an error message?

As far as I can tell, the numbers array wasn't modified in any way. It just did... nothing.

numbers.push is simply a function but you are attempting to find the property located at key 5 from it, which will evaluate to undefined .

 function test() { console.log("test"); } // test[5] evaluates to `undefined` and does nothing console.log(test[5]); // We can even manually set this without messing up the function test[5] = "foo"; // outputs "foo" console.log(test[5]); // outputs our expected value "test" test(); 

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