在 Array[index] 上使用 Array.at()
本文将探讨为何在访问数组元素时,Array.prototype.at()
比 Array[index]
更为理想。
动机
以往访问数组元素时,我习惯使用 Array[index]
,例如 Array[1]
。这是我所熟悉的,也是我学习获取数组元素的方式。
然而,最近一位同事在代码审查中提出:“为什么不使用 Array.prototype.at()
而不是直接使用索引?”
我的代码是:
const element = arr[1];
他建议改为:
const element = arr.at(1);
这种方法让我眼前一亮,因为它看起来非常简洁直观。
如何使用 Array.prototype.at()
Array.prototype.at()
接受一个整数作为参数,并返回数组中的相应元素。
例如,对于数组:
const arr = ["One", "Two", "Three"];
调用:
arr.at(0); // 返回 "One"
这与方括号表示法 array[0]
等效。你可能会好奇,这有什么区别呢?接下来我们将深入探讨使用此方法的优势。
为什么 Array[index] 不理想?
让我们看看一些应该使用 Array.prototype.at()
而不是 Array[index]
的场景。
获取数组的最后一个元素
假设有一个字符串数组:
const sports = ["basketball", "baseball", "football"];
要获取数组的最后一个元素 "football",你可以这样写:
const lastElement = sports[sports.length - 1];
这是正确的方法;但是,使用 Array.prototype.at()
方法可以写得更简洁:
const lastElement = sports.at(-1);
是不是更易读?
类型推断
在 TypeScript 中,方括号表示法不会将 undefined
包含在类型推断中。
const arr: string[] = []; const element = arr[0]; console.log(element); // undefined
element
的类型被推断为 string
,而不是 string | undefined
。
我们期望 TypeScript 在编写此代码时给出编译错误。
通常,我们希望确保访问的数组元素存在。
const arr: string[] = []; const element = arr[0]; if (typeof element === 'string') console.log(element);
奇怪的是,我们正在检查 TypeScript 推断为 string
的元素类型。
你可能会想到使用类型断言:
const element: string | undefined = arr[0];
然而,这并非理想的做法,因为我们不应自己承担编写完美代码的责任。
为了解决这个问题,我们可以采取两种方法:
- 编写类型保护函数
- 使用
noUncheckedIndexedAccess
编译器选项
两种方法都能很好地工作,但如果使用 Array.prototype.at()
,则无需两者兼顾。
const arr: string[] = []; const element = arr.at(0); // string | undefined console.log(element);
如果尝试将 element
插入到类型为 string
的其他值中,则会得到编译错误:
const element = arr[1];
结论
使用 Array.prototype.at()
可以编写更简洁的代码,并避免添加额外的函数和配置。
Array.prototype.at()
在 Mozilla 开发者网络上的解释:链接 (请替换为实际链接)
以上是在 Array[index] 上使用 Array.at()的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)