JavaScript 如何检查数组是否包含特定的值
在本文中,我们将讨论如何构建一个数组,并检查用户所需的特定值是否包含在数组中。
但首先让我们看看如何使用以下语法在JavaScript中创建一个数组-
语法: 以下语法可帮助用户轻松创建数组-
let array = [item_1 , item_2, item_3 , ...];
现在我们已经看到了如何创建一个数组,接下来让我们看看几种方法来检查数组是否包含用户希望查看的任何值。
方法1: 这是最初的、传统的方法,也是任何人在开始时都会考虑的最常见的方法。在这种方法中,我们将运行一个for循环,但在运行for循环之前,我们会初始化数组和我们要查找的值。在这个for循环中,我们将看到如果我们的值存在于数组中,那么我们将返回该变量的索引。如果该值不在数组中,那么我们将退出for循环,并打印一个消息,该值不在数组中。
示例:
HTML
<script>
let fruits_array = [
"mango",
"banana",
"apple",
"pineapple",
"pomegranate",
"orange",
];
let valueChecker = (value) => {
for (let i = 0; i < fruits_array.length; i++) {
let current_value = fruits_array[i];
if (value === current_value) {
return value + " is present at index: " + i;
}
}
return value + " is not included in this array..";
};
console.log(valueChecker("apple"));
console.log(valueChecker("app"));
console.log(valueChecker("banana"));
</script>
输出:
apple is present at index: 2
app is not included in this array..
banana is present at index: 1
方法2: 在分析了上述传统最常用的方法后,现在介绍最新的方法。在该方法中,我们将使用.includes() 方法来检查数组中是否存在该值。如果该值存在,则打印消息说明该值存在于数组中。如果该值不存在,则打印消息说明该值不存在。
示例:
HTML格式
<script>
let fruits_array = [
"mango",
"banana",
"apple",
"pineapple",
"pomegranate",
"orange",
];
let value_1 = "apple";
let value_2 = "app";
console.log(fruits_array.includes(value_1));
console.log(fruits_array.includes(value_2));
</script>
输出:
true
false
方法3: 在这种方法中,我们将使用indexOf() 方法。通过使用这个方法,我们将检查我们要查找的特定元素的索引值是否大于或等于零,如果是,则打印出相应的消息,说明元素存在于某个索引值上。如果数组中没有我们要查找的元素,则显示一个错误消息,说明元素不存在于数组中。
HTML
<script>
let fruits_array = [
"mango",
"banana",
"apple",
"pineapple",
"pomegranate",
"orange",
];
let checkValue = (value) => {
if (fruits_array.indexOf(value) >= 0)
return value + " is present at index : "
+ fruits_array.indexOf(value);
else
return value + " is not present in this array";
};
console.log(checkValue("apple"));
console.log(checkValue("app"));
console.log(checkValue("mango"));
</script>
输出:
apple is present at index : 2
app is not present in this array
mango is present at index : 0