Explain yourselves javascriptcels

40
Jump in the discussion.

No email address required.

Some things:

1. In JS, the bracket syntax is just an alternative way of accessing a property. something.prop is the same as something['prop'], but JS parsing rules don't allow you to use the dot syntax with numbers (so you need to use brackets).

2. All keys in JS are strings. If you try to index an object (arrays are objects) with a number, JS will first convert that to a string.

3. Arrays in JS are known as "exotic objects" and have special behavior -- if you try to set an own property (that is a property which belongs to that object and not its prototype) which also is an integer, it will set that property and then update the length value.

4. This special handling doesn't apply because 0.5 isn't an integer. You've just added the property '0.5' to the object. In effect you have created something like the following:

const items = {
   '0': 1,
   '1': 2,
   '2': 3,
   'length': 3,
   '0.5': 1
}

You could have called your additional property boobies and it would have the same effect, as long as it's not an integer when converted to a string and then converted back into a number.

Jump in the discussion.

No email address required.

K


Give me your money and I'll annoy people with it :space: https://i.rdrama.net/images/16965516366194396.webp

Jump in the discussion.

No email address required.

K

Jump in the discussion.

No email address required.

Link copied to clipboard
Action successful!
Error, please refresh the page and try again.