Array.prototype
、各種 TypedArray 原型和 String.prototype
上的新 at
方法讓存取集合中接近尾端的元素變得更簡單、更簡潔。
從集合尾端存取第 N 個元素是很常見的作業。然而,通常的作法很冗長,例如 my_array[my_array.length - N]
,或者效能不佳,例如 my_array.slice(-N)[0]
。新的 at
方法讓此作業更符合人體工學,方法是將負數索引解讀為「從尾端開始」。前述範例可以用 my_array.at(-N)
表示。
為了統一,正數索引也受支援,且等同於一般的屬性存取。
這個新方法很小,因此其完整語意可以用以下相容的 polyfill 實作來理解
function at(n) {
// Convert the argument to an integer
n = Math.trunc(n) || 0;
// Allow negative indexing from the end
if (n < 0) n += this.length;
// Out-of-bounds access returns undefined
if (n < 0 || n >= this.length) return undefined;
// Otherwise, this is just normal property access
return this[n];
}
關於字串 #
由於 at
最終會執行一般的索引,因此對字串值呼叫 at
會傳回碼元,就像一般的索引一樣。而且就像字串上的一般索引,碼元可能不是您在 Unicode 字串中想要的!請考慮 String.prototype.codePointAt()
是否更適合您的使用案例。
at
方法支援 #
- Chrome: 支援版本 92 以上
- Firefox: 支援版本 90 以上
- Safari: 不支援
- Node.js: 不支援
- Babel: 支援