JavaScript 如何检查数组是否包含某个值
在这篇文章中,我们将学习如何检查一个值是否存在于数组中。为此,我们需要一个要搜索的数组和要检查的目标元素。
JavaScript数组用于存储可以通过单个变量访问的元素列表。
一旦有了目标元素,我们可以执行任何搜索算法来检查数组中是否存在该元素。
1. 线性搜索算法(朴素方法):
在线性搜索算法中,我们将数组的每个元素与目标进行比较。8是下面num数组的一部分。
JavaScript
let num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function check(element) {
for (let i = 0; i < num.length; i++) {
if (num[i] == element)
return element + " is present in the array.";
}
return element + " is not present in the array.";
}
console.log(check(8));
结果
8 is present in the array.
时间复杂度: O(n)
该算法的时间复杂度为O(n),因为我们只需遍历数组一次来检查给定的元素。
空间复杂度: O(1)
该算法的空间复杂度为O(1),因为除了输入数组之外,我们没有使用其他额外的空间。
2. 使用indexOf()函数:
indexOf()函数返回数组中目标元素的索引(如果存在),如果不存在则返回-1。
例如,下面的代码中num数组中没有41。
Javascript
let num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let element = 41;
if (num.indexOf(element) > 0)
console.log(element + " is present.");
else
console.log(element + " is not present.");
输出
41 is not present.
时间复杂度:O(n)
空间复杂度:O(1)
3. 二分查找(Binary Search):
二分查找算法只适用于排序好的数组,并且通过递归不断将数组划分为两个相等的子数组。
Javascript
function bsearch(arr, l, r, x) {
if (r >= l) {
let mid = l + Math.floor((r - l) / 2);
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return bsearch(arr, l, mid - 1, x);
return bsearch(arr, mid + 1, r, x);
}
return -1;
}
let num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// To check if 85 is present or not
console.log("Is 85 present? " + (bsearch(num, 0, num.length, 85) != -1));
// To check if 1 is present or not
console.log("Is 1 present? " + (bsearch(num, 0, num.length, 1) != -1));
输出
Is 85 present? false
Is 1 present? true
时间复杂度: O(log n)
空间复杂度: O(1)
4. filter() 方法:
filter() 方法用于从数组中提取所需的元素。我们首先创建数组,然后在具有检查元素是否存在的方法的数组上使用filter方法。如果数组中存在该元素,则返回一个包含该元素的数组,否则返回一个空数组。
Javascript
let num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function check(element) {
let ans = num.filter(x => x == element);
if (ans.length)
return element + " is present in the array.";
return element + " is not present in the array.";
}
console.log(check(81));
输出
81 is not present in the array.
时间复杂度: O(N)。这里N是数组的大小。
空间复杂度: O(1)。因为它不需要额外的内存。
极客教程