Array.prototype.at

简介: 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];
  };
}

目录
相关文章
|
28天前
|
JavaScript 前端开发
object.assign
object.assign
7 0
|
2月前
|
JSON JavaScript 前端开发
Object.assign
Object.assign
25 1
|
8月前
|
存储 测试技术 C++
map + function 实现替代if - else
代码更简洁:使用map + function可以将多个if-else语句转化为一行代码,使得代码看起来更加简洁易懂。 可读性更好:使用map + function可以将判断逻辑抽象成函数,让代码更具可读性和可维护性。
42 0
|
11月前
Object.assign详解
Object.assign详解
173 0
|
11月前
Array.prototype.concat
Array.prototype.concat
40 0
|
JavaScript API
Array.apply(null,{length: 99}) 逻辑解析
Array.apply(null,{length: 99}) 逻辑解析
62 0
|
JavaScript 开发者
ES6之Object.assign()用法,Object.assign()到底是浅拷贝还是深拷贝?
ES6之Object.assign()用法,Object.assign()到底是浅拷贝还是深拷贝?
6841 1
|
JavaScript 前端开发
Object.assign()详解
Object.assign()详解
Object.assign()详解
|
索引
Array.prototype.flatMap()
Array.prototype.flatMap()
71 0