本文介绍了递归查找数组中的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用递归在JavaScript中的数组中找到最大值.我创建了函数,但无法弄清楚如何递归执行.
I am trying to use recursion to find the maximum value in an array in JavaScript. I created the function, but cannot figure out how to do it recursively.
function Max(a) {
var a = [2,3,5];
return Math.max.apply(Math, a);
}
推荐答案
下面是一个递归函数的示例,该函数采用一个数字数组并比较前两个数字,删除较小的那个,然后在给定的数组上再次调用自身减去删除的数字.
Here is an example of a recursive function that takes an array of numbers and compares the first two, removes the lesser, and then calls itself again on the given array minus the removed number.
function max(numArray)
{
// copy the given array
nums = numArray.slice();
// base case: if we're at the last number, return it
if (nums.length == 1) { return nums[0]; }
// check the first two numbers in the array and remove the lesser
if (nums[0] < nums[1]) { nums.splice(0,1); }
else { nums.splice(1,1); }
// with one less number in the array, call the same function
return max(nums);
}
这是一个jsfiddle: https://jsfiddle.net/t3q5sm1g/1/
Here's a jsfiddle: https://jsfiddle.net/t3q5sm1g/1/
这篇关于递归查找数组中的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!