You might have tried to access the last element in array using arr[arr.length-1]
and wondered if we had support for [-indx]
negative-index but the same wouldn't apply for String
and TypedArrays
as -indx
would be a property on them rather than the index.
Hence we have item()
a proposal on stage-3 is a method on the prototype of the built-in indexable objects: Array
, String
, and TypedArrays
objects, it also supports relative indexing from the end when passed a negative index.
Let us look into few examples:
let nums = [1,2,3];
nums.at(0); // 1
nums.at(-1); // 3
nums.at(100); // undefined
let name = 'ECMA';
name.at(0); // "E"
name.at(-1); // "A"
name.at(100); // undefined
let unit8 = new Uint8Array([1,2,3]);
unit8.at(0); // 1
unit8.at(-1); // 3
unit8.at(100); // undefined
indx
will be converted to 0
for NaN
, null
, +0
, -0
or undefined
If this proposal gets adopted, the following legacy interfaces should be upgradable into ObservableArray
:
- NodeList
- Possibly DOMTokenList as a subclass
- CSSRuleList
- StyleSheetList
- Possibly CSSStyleDeclaration and MediaList, as subclasses
- FileList
Update:
It's worth noting that YUI 2/3 duck-typing on
— Alex Russell (@slightlylate) November 12, 2020item()
means that we'll need a different name for web compat reasons. @_shu suggestedat()