Hacker News new | ask | show | jobs
by sfinx 1886 days ago
If I understand this correctly it is to add negative index support to arrays. How will findIndex work when this is introduced? It currently uses -1 as a return value when no element satisfies the testing function.
4 comments

It’s not adding negative indexes, a negative number will index from the end.

So [0, 1, 2, 3].at(-2) === 2

That would mean getting the last element of the array would be [0,1,2,3].at(-1).

I don't like that very much.

Mind you, I don't like the idea of using [0,1,2,3].at(-0) either...

Don’t think of it as counting from the end of the array — think of it as counting in reverse from the 0th element. .at(1) gets the next element (index 1) while .at(-1) loops around and gets the “previous” element (index 3, in this case).

Or, if it’s more intuitive, you can think of the array index as an unsigned integer where the max is equal to the length of the array. If you try to assign -1 to a uint8, the result will be 255 — the highest possible value (the last index).

Good thing we don't have to stagnate progress just because what we have will never be perfect.
Python also uses negative indexes in this way, see https://docs.python.org/3/library/stdtypes.html#common-seque...
Array.prototype.at would only ever return the value of something in the array at the index requested (or undefined). It'd accept a negative offset, but that's not the index of the thing you're looking for; it's an offset from one end of the array.
You can’t have a negative array index. Passing a negative number will just make this function count backwards instead of forwards.

[1, 2, 3, 4].at(0) === 1

[1, 2, 3, 4].at(1) === 2

[1, 2, 3, 4].at(-1) === 4

findIndex’s behavior is unchanged.