Because `foo.bar` is equivlant to `foo['bar']` in JS so far, and
`array.-1` could break this consistency.
On the other hand, `array.first()` seems not necessary because
`array[0]` is even more handy; `array.last()` looks fine to me.
If someone prefer a more general solution, I recommand `array.get(n)`:
* if n >= 0 && n < array.length: equivlant to array[n]
* if n < 0 && -n < array.length: equivlant to array[array.length + n]
* if n <= -array.length || n >= array.length: throw or return undefined
* if n is not a integer or not a number: throw or return undefined
The last 2 rules make `array.get(n)` less error prone than `array[n]`. I
prefer throwing, but maybe returning undefined is more JS-style?
在 2016/9/27 20:38, Bob Myers 写道:
This is well-traveled territory.
Whatever is or is not implemented, interfaces which have optional
arguments and return scalars in one case and arrays in another case
are a horrible idea.
To my knowledge no-one has ever explained why the following is a bad idea:
```
array.0
array.-1
```
Bob
On Tue, Sep 27, 2016 at 5:42 PM, Nicu Micleusanu <[email protected]
<mailto:[email protected]>> wrote:
I propose to standardize `Array.prototype.first()` and
`Array.prototype.last()`, very similar to underscore `_.first()`
and `_.last()`.
A very basic implementation:
```js
Array.prototype.first = function (n) {
if (!arguments.length) {
return this[0];
} else {
return this.slice(0, Math.max(0, n));
}
};
Array.prototype.last = function (n) {
if (!arguments.length) {
return this[this.length - 1];
} else {
return this.slice(Math.max(0, this.length - n));
}
};
```
_______________________________________________
es-discuss mailing list
[email protected] <mailto:[email protected]>
https://mail.mozilla.org/listinfo/es-discuss
<https://mail.mozilla.org/listinfo/es-discuss>
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss