Javascript 从递归indexOf函数中返回正确的值
计算机模式或思想中的递归在许多编程语言中都存在,包括Javascript。它是一种使用来建立一个函数的特性,该函数反复调用自身,但每次输入都较小,直到代码的预期结果实现。
在本文中,我们将返回Javascript中递归indexOf()函数的正确值。让我们深入了解一下本文。
递归indexOf()函数的准确值
字符串中要查找的第一个出现位置的值由indexOf()方法返回。如果找不到该值,indexOf()方法会返回-1。indexOf()区分大小写。
语法
以下是indexOf()的语法:
indexOf(searchElement)
indexOf(searchElement, fromIndex)
让我们从下面的示例中了解如何从递归函数返回正确的值 indexOf() 在JavaScript中。
示例
在下面的示例中,我们运行脚本来获取递归函数indexOf()的值。在此例中,我们要获取元素”c”的索引。
<!DOCTYPE html>
<html>
<body style="background-color:#EAFAF1">
<script>
function search(array, value) {
if (array[0] === value) {
return 0;
}
if (array.length === 0) {
return -1;
}
const result = search(array.slice(1), value);
return result === -1 ? -1 : result + 1;
}
document.write("The indexof c was:" +
search(["a", "b", "c", "d"], "c"),
);
</script>
</body>
</html>
当脚本被执行时,它将生成一个包含在网页上显示的索引值”c”的输出。
示例
考虑以下示例,我们通过声明一个数组来运行脚本,获取 indexof() 元素”Vespa”,该元素在数组中没有声明,并返回递归的 indexof() 的值。
<!DOCTYPE html>
<html>
<body style="background-color:#E8DAEF">
<p id="tutorial"></p>
<script>
function search(arr, value, i = 0) {
if (i >= arr.length) return -1;
if (arr[i] === value) return i;
return search(arr, value, i + 1);
}
let array = ["Raj", "Kamal", "Vikram", "Ravi"];
document.getElementById("tutorial").innerHTML="The indexof Vespa was: " + (search(array, "Vespa"))
</script>
</body>
</html>
在运行上述脚本时,输出窗口将弹出,显示在网页上“Vespa”的索引为“-1”。之所以显示为“-1”,是因为索引中没有找到值“Vespa”。
示例
执行以下脚本并观察我们如何获得递归的正确值 indexof() 。
<!DOCTYPE html>
<html>
<body style="background-color:#CCCCFF">
<p id="tutorial"></p>
<script>
const array = ['Bheem', 'Nayak', 'Ravi','Dora']
const result = array.indexOf('Ravi');
document.getElementById("tutorial").innerHTML=("The indexof() of required value was:" + result)
</script>
</body>
</html>
当脚本执行时,它将生成一个输出,显示所需值的indexof()为”2 “,该值将显示在网页上。