<!-- TOC -->

  • 绝对索引办法之.at函数
  • 对字符串的补充
  • 参考:
  • 社交信息 / Social Links:

    • (Welcome to pay attention, 欢送关注)

<!-- /TOC -->

Array.prototype 上的新的新办法 --- at 函数,能够让咱们更加不便的拜访到数组 和 字符串开端的元素。

在理论开发中,我常常须要去拜访到数组或者是字符串中开端的某个元素的。

然而吧,通常应用的法子不是很好的,比方 my_array[my_array.length - N]

或者是

应用可能没有什么性能的操作,比方 my_array.slice(-N)[0]

应用这个新的函数办法 .at() ,它更加合乎咱们人本身的惯例思考。它是这样的,它将负指数解释为“从最初”。

什么意思呢?

就是,参数是正数,就示意倒数第几个; 负数就示意负数第几个,相当于一般的属性拜访。

后面的示例能够示意为 my_array.at(-N)

比方:

var arr = [1, 2, 5, 9, 78]// 第0个console.log(arr.at(0)) // 1// 负数第一个console.log(arr.at(1)) // 2// 倒数第一个console.log(arr.at(-1)) // 78// 倒数第二个console.log(arr.at(-2)) // 9

是不是很合乎咱们的思考逻辑呢?

这个新办法足够小,它的残缺语义能够被上面这个兼容的 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() 是否更适宜您的用例。

应用 codePointAt():

'ABC'.codePointAt(1);          // 66'\uD800\uDC00'.codePointAt(0); // 65536'XYZ'.codePointAt(42); // undefined

动下小手

  • 欢送关注我的GitHub:@huangyangquang ⭐⭐
  • 欢送关注我的公众号:前端学长Joshua