zoukankan      html  css  js  c++  java
  • 数组将要新增的方法:array.at(index)

    方括号语法的局限性

    通常按索引访问数组元素的方法是使用方括号语法 array[index]:

    const fruits = ['orange', 'apple', 'banana', 'grape'];
    
    const item = fruits[1];
    item; // => 'apple'

    表达式 array[index] 的执行结果是位于 index 位置的数组元素项,JavaScript 中数组的索引从 0 开始,这些你肯定知道。

    通常方括号语法是一种通过正索引(>= 0)访问数组元素的方法。它的语法简单易读。

    但有时我们希望从末尾开始访问元素。例如:

    const fruits = ['orange', 'apple', 'banana', 'grape'];
    
    const lastItem = fruits[fruits.length - 1];
    lastItem; // => 'grape'

    fruits[fruits.length-1] 是访问数组最后一个元素的方式,其中fruits.length-1 是最后一个元素的索引。

    问题在于方括号不允许直接从数组末尾访问元素,也不能接受负索引。

    幸运的是,一项新的提案(截至2021年1月的第3阶段)将 at() 方法引入了数组(以及类型化数组和字符串),并解决了方括号的许多限制。

    https://www.51220.cn 51220网站目录

    array.at() 方法

    简而言之,array.at(index) 用来访问处于 index 位置的元素。

    如果 index 是一个正整数 >= 0,则该方法返回这个索引位置的元素:

    const fruits = ['orange', 'apple', 'banana', 'grape'];
    
    const item = fruits.at(1);
    item; // => 'apple'

    如果 index 参数大于或等于数组长度,则像方括号语法一样返回 undefined:

    const fruits = ['orange', 'apple', 'banana', 'grape'];
    
    const item = fruits.at(999);
    item; // => undefined

    当对 array.at() 方法使用负索引时,会从数组的末尾访问元素。

    例如用索引 -1 来访问数组的最后一个元素:

    const fruits = ['orange', 'apple', 'banana', 'grape'];
    
    const lastItem = fruits.at(-1);
    lastItem; // => 'grape'

    下面是更详细的例子:

    const vegetables = ['potatoe', 'tomatoe', 'onion'];
    
    vegetables.at(0); // => 'potatoe'
    vegetables.at(1); // => 'tomatoe'
    vegetables.at(2); // => 'onion'
    vegetables.at(3); // => undefined
    
    vegetables.at(-1); // => 'onion'
    vegetables.at(-2); // => 'tomatoe'
    vegetables.at(-3); // => 'potatoe'
    vegetables.at(-4); // => undefined

    如果 negIndex 是一个负索引 < 0,那么 array.at(negIndex) 将会访问位于索引 array.length + negIndex 处的元素。例如:

    const fruits = ['orange', 'apple', 'banana', 'grape'];
    
    const negIndex = -2;
    
    fruits.at(negIndex);              // => 'banana'
    fruits[fruits.length + negIndex]; // => 'banana'

    总结

    JavaScript 中的方括号语法是按索引访问项目的常用方法。只需将索引表达式放在方括号 array[index] 中,然后既可以获取在该索引处的数组项。

    但是有时这种方式并不方便,因为它不接受负索引。所以要访问数组的最后一个元素,需要用这种方法:

    const lastItem = array[array.length - 1];

    新的数组方法 array.at(index) 使你可以将索引作为常规访问器访问数组元素。此外,array.at(index)接受负索引,在这种情况下,该方法从头开始获取元素:

    const lastItem = array.at(-1);

    现在只需要把 array.prototype.at polyfill 包含到你的应用程序

  • 相关阅读:
    同node上,两个pod通过svc访问不通
    Prometheus基于service自动添加监控
    systemd 服务管理编写
    kubernetes 控制器详解【持续完善中】
    tcpdump抓包工具
    Zabbix日志监控插件
    Spring WebFlux之HttpHandler的探索
    知秋源码解读分享系列
    Spring Framework 5.0.0.M3中文文档 翻译记录 Part I. Spring框架概览1-2.2
    Spring Framework 5.0.0.M3中文文档 翻译记录 introduction
  • 原文地址:https://www.cnblogs.com/qianxiaox/p/15070852.html
Copyright © 2011-2022 走看看