我需要找到哪个变量具有最大值。
通常我会做这样的事情:
var Dimensions = [Height, Length, Depth];
var biggestSide = Math.max.apply(Math, Dimensions);
但在此之后我需要对变量做一些事情。
是否有办法在不使用数组或一系列 if
语句的情况下识别具有最大值的 var?
最佳答案
您可以使用switch声明
var biggestSide = Math.max(Height, Length, Depth);
switch (biggestSide) {
case Height:
...
break;
case Length:
...
break;
case Depth:
...
break;
}
阅读您的评论后:
@mplungjan - in brief, the vars Height, Length and Width and the max values from arrays themselves. I need to identify the array that has the largest value so I can do something with the vars that are pushed to that array. – MeltingDog
我认为这样的事情就是你所追求的
var maxHeight = Math.max.apply(Math, Height);
var maxLength = Math.max.apply(Math, Length);
var maxDepth = Math.max.apply(Math, Depth);
var biggestSide = Math.max(maxHeight, maxLength, maxDepth);
switch (biggestSide) {
case maxHeight:
// Do something with Height
break;
case maxLength:
// Do something with Length
break;
case maxDepth:
// Do something with Depth
break;
}
注意,对于 ES6,您可以使用 spread operator而不是应用函数:
var maxHeight = Math.max(...Height);
关于javascript - 不使用数组检测具有最大值的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32243666/