gpt4 book ai didi

javascript - 不使用数组检测具有最大值的变量?

转载 作者:行者123 更新时间:2023-12-03 09:03:30 25 4
gpt4 key购买 nike

我需要找到哪个变量具有最大值。

通常我会做这样的事情:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com