提高数组访问效率:array.at()方法详解

在现代的 JavaScript 编程中,我们通常会处理各种数组操作。在以往,我们经常使用 array[] 这种方式来获取数组中的元素,但其实有一个更安全和可靠的替代方法:array.at()

介绍 array.at()

相比于使用 array[]array.at() 具有更强大的功能和更好的错误处理机制,可以防止数组越界错误。它接受一个索引作为参数,并返回该索引处的元素

实操

一般获取元素

js 复制代码
const colors = ['pink', 'orange','banana']
console.log(colors[1])
console.log(colors.at(1))

字符串

js 复制代码
const words = 'herry'
console.log(words[3])
console.log(words.charAt(3))
console.log(words.at(3))

获取最后n个元素

js 复制代码
const colors = ['pink', 'orange','banana']
console.log(colors[colors.length - 1])
console.log(colors.at(-1))

const n = 2
console.log(color[color.length - n])
console.log(color.at(-n))

获取不在数组中的元素

js 复制代码
const colors = ['pink', 'orange','banana']
console.log(colors[colors.length])  //undefined
console.log(colors.at(-10)) //undefined

兼容性

可以看到大概现代90%浏览器都支持Array.at()方法 但是有些比较古老的Chrome Edge或者Safari并不支持 更别说什么IE。。 那么如何能够向下兼容 如何让较低浏览器版本也能运行Array.at()不报错 一般是俩种解决方案 transpiling或者polyfilling

Transpiling(语法转化)

在日常开发中,通常会使用工具如Babel来将新的语法转化为老的语法,以确保在老版本浏览器引擎上也能正常运行 这个过程叫做"transpiling" 说这么多就是新语法降级旧语法

js 复制代码
 if (!Array.prototype.at) {
    if (index < 0) {
      index = arr.length + index;
    }
    if (index < 0 || index >= arr.length) {
      return undefined;
    }
    return arr[index];
  } else {
    return arr.at(index);
  }

那么通过这个Transpiling就可以确保代码的兼容性 还是比较简单的

Polyfilling(补充新功能)

另一种方法是通过"polyfilling" 来为老的js环境添加缺失的功能 Polyfilling就是自己来实现Array.at()方法 以便在不支持该方法的环境中使用 就是想用就自己造!

  • Object.definePropertyArray.prototype对象添加一个名为at的新属性
  • value: function(index) 部分是新属性at的值 获取数组中的元素
  • 中间部分core代码和上面讲解一样
  • writable: true, 表示们可以在运行时修改Array.prototype.at方法的实现
  • configurable: true,表示这个属性可以被修改、删除,或者重新定义。两者可以增加at灵活性
js 复制代码
if (!Array.prototype.at) {
  Object.defineProperty(Array.prototype, 'at', {
    value: function(index) {
      if (index < 0) {
        index = this.length + index;
      }
      if (index < 0 || index >= this.length) {
        return undefined;
      }
      return this[index];
    },
    configurable: true,
    writable: true
  });
}

扩展

一个Array.at()语法都要这么大费周章那要是还有其他什么箭头函数 Promise 模板字符串这些咋搞?不用担心!一般开发出现的问题前人也早已经遇到了 我们乖乖乘凉就行!

core-js

core-js是JavaScript的模块化标准库 包括ECMAScript到2023的polyfill:Promise, symbols, ECMAScripts提案等等 也可以只按需加载

代码示例

js 复制代码
import 'core-js/actual';

Promise.resolve(42).then(it => console.log(it)); // => 42

Array.from(new Set([1, 2, 3]).union(new Set([3, 4, 5]))); // => [1, 2, 3, 4, 5]
[1, 2].flatMap(it => [it, it]); // => [1, 1, 2, 2]

(function * (i) { while (true) yield i++; })(1)
  .drop(1).take(5)
  .filter(it => it % 2)
  .map(it => it ** 2)
  .toArray(); // => [9, 25]
structuredClone(new Set([1, 2, 3])); // => new Set([1, 2, 3])

还有没有什么办法?

但假设你的需求很刁钻 你必须在一个很偏门很古老的浏览器也能怎么怎么样 core-js没有想要的polyfill怎么办呢 那确实也没办法-,- 自家的需求最终也还得自家来做

next.js也还是自己来做polyfill 毕竟具体情况用core-js也不总是能奏效

希望有收获!点赞收藏ooo✨

相关推荐
摘星编程3 小时前
OpenHarmony + RN:Placeholder文本占位
javascript·react native·react.js
摘星编程7 小时前
React Native + OpenHarmony:Spinner旋转加载器
javascript·react native·react.js
普通网友8 小时前
新手必看!HCCDA-HarmonyOS & Cloud Apps 实验保姆级教程
javascript·angular.js
用户新8 小时前
V8引擎 精品漫游指南--Ignition篇(上) 指令 栈帧 槽位 调用约定 内存布局 基础内容
前端·javascript
Next_Tech_AI8 小时前
别用 JS 惯坏了鸿蒙
开发语言·前端·javascript·个人开发·ai编程·harmonyos
-凌凌漆-8 小时前
【vue】选项式api与组合式api
前端·javascript·vue.js
2601_949809598 小时前
flutter_for_openharmony家庭相册app实战+通知设置实现
android·javascript·flutter
可触的未来,发芽的智生9 小时前
发现:认知的普适节律 发现思维的8次迭代量子
javascript·python·神经网络·程序人生·自然语言处理
phltxy11 小时前
Vue3入门指南:从环境搭建到数据响应式,开启高效前端开发之旅
前端·javascript·vue.js
摘星编程12 小时前
OpenHarmony + RN:ProgressBar进度条组件
javascript·react native·react.js