从JavaScript中的递归indexOf返回正确的值?
您可以创建自己的函数。如果找到搜索值,则返回索引,否则返回-1。
示例
以下是代码-
const indexOf = (arrayValues, v, index = 0) =>
index >= arrayValues.length
? -1
: arrayValues[index] === v
? index
: indexOf(arrayValues, v, index + 1)
console.log(indexOf(["John", "David", "Bob"], "Adam"))
console.log(indexOf(["Mike", "Adam", "Carol", "Sam"], "Sam"))要运行上述程序,您需要使用以下命令-
node fileName.js.
在这里,我的文件名为demo321.js。
输出结果
这将产生以下输出-
PS C:\Users\Amit\javascript-code> node demo321.js -1 3