我使用array.forEach()实现了线性搜索算法,但是我不知道为什么它不返回我正在搜索的值的索引:
function linearSearch(array, value) {
array.forEach((currentValue, index) => {
if (value === currentValue) {
return index;
}
});
return -1; //if not found, return -1
}
const arr = [1,2,3,4,5];
const found = linearSearch(arr, 3);
console.log(found); //should be 2?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Linear Search</title>
</head>
<body>
<script src="main.js"></script>
</body>
</html>