递归求嵌套数组中最大值

今早在 https://attachments.me/hirehack/public/computer.html 做题,有一题是 递归求嵌套数组中最大值:

/*
This challenge requires that, given as input an array which may contain:
 - integer values.
 - inner-arrays of integer values.
 - any recursive combination thereof.
 Return the largest value contained in the array or any of its sub-arrays.

Input: [1, [2, [3, 4]], [5, [6, 7]]]

Output: 7
*/

分享一下我的代码:

function recursiveMax(input){
    var nums=[];
    for(var i=0;i<input.length;i++){
        var obj=input[i];
        if(obj instanceof Array){
            nums.push(recursiveMax(obj));
        }
        else{
            nums.push(obj);
        }
    }
    return Math.max.apply(null,nums);
}

//Test
recursiveMax([1,[[2,3],4,5,6,7],8,9,10]);//output 10

欢迎交流。

posted @ 2012-04-15 10:30  artwl  阅读(989)  评论(2编辑  收藏  举报

个人简介

var ME = {
	"name": "土豆/Artwl",
	"job": "coding",
	"languages": [
		"JS", "HTML",
                "CSS", "jQuery"
		"MVC",".NET",
		"设计模式"
	],
	"hobby": [
		"阅读", "旅游",
		"音乐", "电影"
	]
}
TOP