嗨,我从以下JavaScript代码中获取未定义的内容。我想要一个调试JavaScript的工具,Webstorm是最好的吗?
//input
var inputArray = [1, 2, 3, 4, 5, 5, 5, 6, 66];
var searchValue = 2;
//output
var arrayLength = inputArray.length;
var arrayCurrent = inputArray;
var currentIndex = arrayLength;
function binarySearch() {
currentIndex = Math.floor(arrayCurrent.length / 2);
if (searchValue == arrayCurrent[currentIndex]) {
var x=currentIndex;
return x;
} else if (searchValue > arrayCurrent[currentIndex]) {
arrayCurrent = arrayCurrent.slice(currentIndex + 1);
binarySearch();//recursive call
} else if (searchValue < arrayCurrent[currentIndex]) {
arrayCurrent = arrayCurrent.slice(0, currentIndex - 1);
binarySearch();//recursive call
}
}
var found=binarySearch();
console.log("the index of the searched value is: " + found);
Console output:
the index of the searched value is: undefined
答案 0 :(得分:5)
只有在函数调用自身时才会发生递归。但在这种情况下,你可以使用一个循环。
我在Oliver Caldwell's blog上找到了以下示例:
var inputArray = [1, 2, 3, 4, 5, 5, 5, 6, 66];
var searchValue = 6;
function binarySearch(searchValue, inputArray) {
var minIndex = 0,
maxIndex = inputArray.length - 1,
currentIndex,
currentElement;
while (minIndex <= maxIndex) {
currentIndex = (minIndex + maxIndex) / 2 | 0;
currentElement = inputArray[currentIndex];
if (currentElement < searchValue)
minIndex = currentIndex + 1;
else if (currentElement > searchValue)
maxIndex = currentIndex - 1;
else
return currentIndex;
}
return -1;
}
var found = binarySearch(searchValue, inputArray);
console.log("The index of the searched value is: " + found);
&#13;