admin管理员组

文章数量:1336213

I was curious to know if there is a way in Javascript or JQuery to make a variable equal the lowest of a set of values simply.

So assuming I have:

X = 1
Y = 2

Var Z = lowest of X or Y

I know I could do an if statement that basically reads

if(X < Y){
    Z = X
} else {
    Z = Y
}

I was mainly just curious if something existed to do this in one line.

Thanks!

I was curious to know if there is a way in Javascript or JQuery to make a variable equal the lowest of a set of values simply.

So assuming I have:

X = 1
Y = 2

Var Z = lowest of X or Y

I know I could do an if statement that basically reads

if(X < Y){
    Z = X
} else {
    Z = Y
}

I was mainly just curious if something existed to do this in one line.

Thanks!

Share Improve this question edited Aug 23, 2017 at 12:45 Mihai Alexandru-Ionut 48.4k14 gold badges105 silver badges132 bronze badges asked Aug 23, 2017 at 9:17 Farrell ColemanFarrell Coleman 793 silver badges16 bronze badges 1
  • I need to ask harder questions :p I get too many correct answers and don't know who to mark as correct lol – Farrell Coleman Commented Aug 23, 2017 at 9:19
Add a ment  | 

8 Answers 8

Reset to default 8

Use Math.min function: Math.min(X, Y)

You should use ternary operator.

let z = x < y ? x : y

Another method is to use Math.min function.

let z = Math.min(x, y);

You can use a ternary operator.

let X = 1;
let Y = 2;

let Z = (X<Y?X:Y);
console.log(Z);

this is what you need:

var Z = X < Y ? X : Y;

You can use,

X = 1;
Y = 2;
Z = Math.min(X, Y);

or

X = 1;
Y = 2;
Z = (X < Y) ? X : Y;

var X = 1;
var Y = 2;
document.write(Math.min(X,Y));

Try to use this:

let Z = Math.min(X, Y);

you could do this:

var z = x < y ? x : y

本文标签: javascriptAssign lowest of two valuesStack Overflow