迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中如何检查是否存在数组索引

作者:迹忆客 最近更新:2022/12/15 浏览次数:

要检查数组索引是否存在,请访问特定索引处的数组并检查结果是否不等于 undefined。 如果结果不等于 undefined,则数组索引存在。

const arr = ['a', 'b'];

if (arr[3] !== undefined) {
  // 👉️ index 3 exists in the array
}

基于 JavaScript 的索引为 0。

我们访问索引为 3 的数组并检查结果是否不等于 undefined。

由于数组只有 2 个元素,数组中的最后一个索引为 1。因此,条件永远不会满足,if 块不会运行。

或者,我们可以检查数组的长度。

使用 length 属性检查数组索引是否存在,例如 if (arr.length > 5) {}。 如果数组的长度大于 N,则索引 N 保证存在于数组中。

const arr = ['a', 'b'];

if (arr.length > 5) {
  // 👉️ index 5 exists in the array
}

我们检查数组的长度是否大于 5。如果数组的长度大于 5,则保证索引 5 存在于数组中。

JavaScript 中的索引从零开始,因此数组中的最后一个索引等于 array.length - 1

如果数组的长度为 10,则其最后一个索引为 10 - 1 = 9。

检查数组索引是否存在的更新方法是使用可选链接。

使用可选的链接运算符检查数组索引是否存在,例如 const firstIndex = arr?.[1]。 如果索引存在,可选的链接运算符将返回数组元素,否则返回未定义。

const arr = ['a', 'b'];

const firstIndex = arr?.[1];
console.log(firstIndex); // 👉️ b

if (firstIndex !== undefined) {
  // 👉️ index 1 exists in the array
}

const fifthIndex = arr?.[5];
console.log(fifthIndex); // 👉️ undefined

我们使用可选的链接运算符 ?. 来访问索引 1 和 5 处的数组元素。

索引 1 处的数组元素存在,因此将其值分配给 firstIndex 变量。

索引 5 处的数组元素不存在,因此可选的链接运算符短路返回未定义。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便