admin管理员组

文章数量:1323730

I've been looking at simple JS exercises and I would appreciate it if you showed me how to approach this question or, even better, provide a solution that I can take a look at. Help much appreciated.

EDIT: I would also appreciate any simple working example of the function in use.

I've been looking at simple JS exercises and I would appreciate it if you showed me how to approach this question or, even better, provide a solution that I can take a look at. Help much appreciated.

EDIT: I would also appreciate any simple working example of the function in use.

Share Improve this question asked Jun 5, 2012 at 23:55 WK_of_AngmarWK_of_Angmar 3152 gold badges4 silver badges8 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 5
function whatDidYouTry() {
    return Math.max.apply(null, arguments);
}

There's no need to create a new function as one already exists:

Math.max(num1, num2, num3);

Creating a new function is just extra overhead with no value added.

function get_max(num1, num2, num3)
{
    var max = Math.max(num1, num2, num3);
    return max;
}

alert(get_max(20,3,5)); // 20

DEMO.

Taking a crack at it.

function threeNumberSort(a,b,c) {
    if (a<b) {
        if (a<c) {
            if (b<c) {
                console.log(a + ", then " + b + ", then " + c);
            } else {
                console.log (a + ", then " + c + ", then " + b);
            }
        } else {
            console.log (c + ", then " + a + ", then " + b);
        }
    } else {
        if (b<c) {
            if (a<c) {
               console.log (b + ", then " + a + ", then " + c); 
            } else {
                console.log (b + ", then " + c + ", then " + a);
            }
        } else {
            console.log (c + ", then " + b + ", then " + a);
        }
    }
}

threeNumberSort(1456,215,12488855);

This will print on your console:

215, then 1456, then 12488855

I have used the algorithm I found on this page. More efficient ones probably exist out there.

This is the manual code I came up with using functions and else if statements:

function maxOfThree(a, b, c) {
    if ((a >= b) && (a >= c)) { 
        return a;
    } else if ((b >= a) && (b >= c)) {
        return b;
    } else {
        return c;
    }
}

console.log(maxOfThree(343,35124,42));

本文标签: