JavaScript 如何检查某个数组索引是否存在值 您所在的位置:网站首页 java数组判断是否存在某个值 JavaScript 如何检查某个数组索引是否存在值

JavaScript 如何检查某个数组索引是否存在值

2024-07-14 09:16| 来源: 网络整理| 查看: 265

JavaScript 如何检查某个数组索引是否存在值

本文中,我们将学习如何在JavaScript中检查某个数组索引是否存在值。数组用于将多个值存储在一个变量中。数组中的每个值都有一个数值索引,从零开始。您可以使用它们的索引访问数组中的值。在JavaScript中,有不同的方法来检查某个数组索引是否存在值。

使用typeof运算符 使用in运算符 使用hasOwnProperty()方法

方法: 将使用以下方法来检查某个数组索引是否存在值。

1.使用typeof运算符: 在JavaScript中,typeof运算符以字符串形式返回其操作数的数据类型。操作数可以是任何对象、函数或变量。如果值是未定义的,则它不存在。

语法:

typeof (operand)

示例: 在这个示例中,我们将看到使用 typeof 操作符来检查值。

Javascript let arr = [1, 2, 3, 4, 5]; let value = 3;    if (typeof arr[value] !== "undefined") {     console.log(`Value {value} exists          at index{value - 1}`); } else {     console.log(`Value {value} doesn't          exist at index{value - 1}`); }

输出

Value 3 exists at index 2

2. 使用in运算符: The in运算符用于检查对象中是否存在给定的属性或索引。对于数组,你可以使用in运算符来检查索引是否存在。

语法:

prop in object

示例: 在这个示例中,我们将看到 in 运算符 的使用。

Javascript let arr = [1, 2, 3, 4, 5]; let n = 3;    if (n in arr) {     console.log(`Value {n} exists          at index{arr.indexOf(n)}`); } else {     console.log(`Value ${n} does not          exist in the array`); }

输出

Value 3 exists at index 2

然后,代码使用if-else语句来检查in运算符的结果,并在控制台打印相应的消息。

3. 使用hasOwnProperty()方法: hasOwnProperty()方法用于检查对象是否具有特定的属性或索引。对于数组,您可以使用此方法来检查索引是否存在。

语法:

object.hasOwnProperty( prop )

示例: 在这个示例中,我们将看到使用 hasOwnProperty()方法 。

Javascript const arr = ['Geeksforgeeks', 'GFG', 'gfg'];    if (arr.hasOwnProperty(1)) {     console.log(arr[1]);     console.log('The index exists in the array') } else {     console.log('The specified index does NOT exist'); }

输出

GFG The index exists in the array


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有