简体   繁体   中英

How does the following JavaScript syntax work? array['push']('5')

While reverse-engineering some obfuscated JavaScript code for a CTF, I came across the following syntax:

array['push']('5');

It pushes '5' at the end of the array, which seems logical, but I just do not understand why this syntax works, since I haven't managed to find anything about it (not on the Mozilla Developer Network , not on the W3C website , and the latest ECMAScript specification is a bit too dense for me to understand).

I'm thinking it has something to do with arrays being a special case of objects, but I'm not versed enough in JavaScript to figure it out.

In JavaScript, you can access object properties either using dot notation or square brackets. So object.propertyname is equivalent to object['propertyname'] . Normally we use square brackets when the property name is calculated dynamically or is not a valid identifier (eg it contains special characters). But there's nothing prohibiting using it in other contexts. So array['push'] is equivalent to array.push , and therefore array['push'](5) is equivalent to array.push(5) .

array['push']('5'); translates to:

const array = [];
array.push('5');

Since push is always a method on arrays, it can be accessed via association like ['push'] or directly as a property.

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