最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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.

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.

Share asked Jan 14, 2018 at 23:18 VinceVince 4,2323 gold badges37 silver badges59 bronze badges 2
  • 1 because that simply evaluates to undefined - any property (functions are just properties in javascript anyway) can have properties ... – Jaromanda X Commented Jan 14, 2018 at 23:20
  • 3 Because it is just accessing the property named 5 on the property named push. There isn't a syntax error there, just a logic one – Patrick Evans Commented Jan 14, 2018 at 23:21
Add a ment  | 

1 Answer 1

Reset to default 9

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();

发布评论

评论列表(0)

  1. 暂无评论