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 05 Answers
Reset to default 5function 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));
本文标签:
版权声明:本文标题:javascript - How would I create a function that takes three numbers as arguments and returns the largest of them? - Stack Overfl 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742122435a2421780.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论