javascript / jquery - 选择两个数字中较大的一个 [英] javascript / jquery - select the larger of two numbers

查看:152
本文介绍了javascript / jquery - 选择两个数字中较大的一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用javascript来选择两个数字中较大的数字。我知道我可以写一个if语句,但我想知道是否有某种数学运算或某事使这更有效率。下面是我如何使用if语句:

I'm trying to use javascript to select the greater of two numbers. I know I can write an if statement, but I'm wondering if there's some sort of Math operation or something to make this more efficient. Here's how I'd do it with an if statement:

if (a > b) {
    c = a;
}  
else {
    c = b;
}


推荐答案

最大函数我认为....

You're looking for the Max function I think....

var c = Math.max(a, b);

此函数还需要两个以上的参数:

This function will take more than two parameters as well:

console.log(Math.max(4,76,92,3,4,12,9));
//outputs 92

如果你有一个未知长度的列表,你可以使用 apply ...

If you have a list of unknown length to run through max, you can use apply...

var arrayOfNumbers = [4,76,92,3,4,12,9];
console.log(Math.max.apply(null, arrayOfNumbers));
//outputs 92

这篇关于javascript / jquery - 选择两个数字中较大的一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆