Array.prototype.at

概念

Array.prototype.at方法根据索引位置,返回数组中对应的元素。

语法

arr.at(index)

参数

  • index 需要检索的位置。

返回值

  • 返回数组中索引的元素。如果索引不在数组范围内,则返回undefined。

描述

  1. 当参数index是整数时。
    1.1、 当参数index不存在时,默认为0;
    1.2、 当参数index为正整数时,从数组起始位置开始向数组末尾依次索引,即从前向后依次索引;
    1.3、 当参数index为负整数时,从数组末尾位置开始向数组的起始位置依次索引,即从后向前依次索引。
    1.4、 当参数index不在数组范围内,则返回undefined。
  • 当 index 不存在时,等价于0;
  • 当 index 为正整数时;
  • 当 index 为负整数时,等价于 index + arr.length。
0 1 2 3 4
-5 -4 -3 -2 -1
  1. 当参数不是整数时。
    将参数转化成整数,在按照上面的方式判断。

注意 at方法中参数不能将BigInt转化成数值。

讨论参数index为什么不能将BigInt转化成数值?猜一猜转化规则?

公布参考答案:
at方法中参数进行了隐式转换 index = Math.floor(index)。

例子

例一、参数不存在

let arr = ['前', '端', '咖', '官', '网'];
console.log(arr.at());  // 前

例二、参数为0时

let arr = ['前', '端', '咖', '官', '网'];
console.log(arr.at(0));  // 前

例三、参数为正整数时

let arr = ['前', '端', '咖', '官', '网'];
console.log(arr.at(1));  // 端

例四、参数为负整数时

let arr = ['前', '端', '咖', '官', '网'];
console.log(arr.at(-1));  // 网

例五、参数不在数组范围内

let arr = ['前', '端', '咖', '官', '网'];
console.log(arr.at(5));  // undefined
console.log(arr.at(-6));  // undefined

例六、参数是浮点数时,向下取整

let arr = ['前', '端', '咖', '官', '网'];
let result = arr.at(1.9);
console.log(result);  // '端'

例七、参数是字符串时

let arr = ['前', '端', '咖', '官', '网'];
let result = arr.at('1.9');
console.log(result);  // '端'

例八、参数是布尔值时

let arr = ['前', '端', '咖', '官', '网'];
let result = arr.at(true);
console.log(result);  // '端'

例九、参数是BigInt时

let arr = ['前', '端', '咖', '官', '网'];
let result = arr.at(1n);  // Uncaught TypeError: Cannot convert a BigInt value to a number
console.log(result);

实现 at 方法

if (!Array.prototype.at) {
  Array.prototype.at = function (index) {
  	index = Math.floor(index);
  	
    if (index === undefined) {
      index = 0;
    } else if (index < 0) {
      index = index + this.length;
    }
    retun this[index];
  };
}

公众号

posted @ 2023-01-19 08:24  前端咖  阅读(187)  评论(0编辑  收藏  举报