JavaScript 中如何检查是否存在数组索引
要检查数组索引是否存在,请访问特定索引处的数组并检查结果是否不等于 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 处的数组元素不存在,因此可选的链接运算符短路返回未定义。
相关文章
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
将 NumPy 数组转换为 Pandas DataFrame
发布时间:2024/04/21 浏览次数:111 分类:Python
-
本教程介绍了如何使用 pandas.DataFrame()方法从 NumPy 数组生成 Pandas DataFrame。
如何将 Pandas Dataframe 转换为 NumPy 数组
发布时间:2024/04/20 浏览次数:176 分类:Python
-
本教程介绍如何将 Pandas Dataframe 转换为 NumPy 数组的方法,例如 to_numpy,value 和 to_records
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。