5 ms·
Am I reading this correctly — it's an alias for arr[i] and str[i]? I know languages like Ruby have arr.at(i), but why?
by ezekg 5y ago
Am I reading this correctly — it's an alias for arr[i] and str[i]? I know languages like Ruby have arr.at(i), but why?
- twoodfin 5y agoA quick read suggests that it adds negative indexing from the end of the array.
- Pxtl 5y agoImho that violates the principle of least astonishment - that "at" would have such different behavior from "[]" for negative numbers.
- pininja 5y agoAccessing negative indexes currently returns undefined. This adds support for indexing from the end of an array with negative numbers.
- franciscop 5y agoThis works, but not the way you'd think: const arr = []; arr[-1] = 'Hello world'; console.log(arr[-1]); // Hello world Instead of using the negative index, it stringifies the "-1" and uses it as the key of an object both when writing and reading. Thus, arr.length still remains 0
- maweki 5y agoIt's a function object then.
- nvartolomei 5y agoProposal hosted on GitHub explains the reasoning behind it https://github.com/tc39/proposal-relative-indexing-method https://github.com/tc39/proposal-relative-indexing-method
- antris 5y agoIn addition to negative index support, a function is more easily composable e.g. converting a list of indices to a list of objects: `indices.map(myObjectArr.at)` I've lost count on how many times I've wrote this function manually.
- bidirectional 5y ago> `indices.map(myObjectArr.at)` That works in this case, but eta-reduction is not generally safe in Javascript due to the variadic nature of many functions, so I wouldn't recommend it in production code. For example `indices.forEach(console.log)` does not work as one would expect.
- antris 5y agoBetter a function that works in some cases than not having a function at all. Also, by using TypeScript definitions you pretty much always know what's coming in and going out and VS Code will yell at you if you're trying to do something stupid.
- e1g 5y agoA function that works in some cases will be a nightmare to debug. The pattern of `indices.map(myObjectArr.at)` is discouraged in JS because it often fails in unexpected ways. For example - ["1","2"].map(parseFloat) // works as expected ["1","2"].map(parseInt) // nope
- antris 5y agoI've learned ages ago that parseInt cannot be used like this, so it's not a problem for me, but I thought linters already take care of this case? Also I wasn't talking about using parseInt, a broken function like this so I'm not sure what the quirks of old, widely known bad parts of Javascript have to do with using functions as arguments, which is one of the most powerful features of the language.
- 5y ago