在javascript中找不到if语句的给定范围内的数字

时间:2017-04-03 10:16:45

标签: javascript

我有3个输入数字最小值和最大值

  • 如果数字在最小值和最大值之间,则函数应返回数字
  • 如果number小于min,则函数应返回min
  • 如果number大于max,则函数应返回max

    [{side: Buy, price: 100}, {side: Buy, price: 110}, {side: Sell, price: 200}, {side: Buy, price: 150} ] 
    

我尝试过这样做但没有if语句就无法做到 提示:需要使用数学函数

3,4,5 -> 4
3,1,7 -> 3
9,1,7 -> 7 

如果没有if或任何条件语句,如何实现它?

4 个答案:

答案 0 :(得分:1)

此处首先检查numbermax的最大值,然后检查min和其他比较的最小值。

const minCalculator = (number, min, max) => Math.max(min, Math.min(number, max))

const test1 = minCalculator(3,4,5)
const test2 = minCalculator(3,1,7)
const test3 = minCalculator(9,1,7)

console.log(test1, test1 === 4)
console.log(test2, test2 === 3)
console.log(test3, test3 === 7)

答案 1 :(得分:0)

Math.min()返回数组中的最小值。

Math.min(3,4,5) will output 3
Math.max(3,4,5) will output 5

你可以这样做:

var x = Math.min(number,maxNumber) //if the number is bigger than the maximum, x will keep the maximum, if the number is smaller than the max, x will keep number.

然后

var x = Math.max(x,minNumber) //same principal

x将最终保存一个在您需要的范围内的数字。

这里有一个你正在寻找的东西: jsFiddle

答案 2 :(得分:0)

如果只使用3个数字,你可以尝试发送值作为一个数组,找到min max并将它们取出,在这个返回数组之后。

ALTER DATABASE database-name ADD STORAGE ON storage-path

重要!!只有在数组中有3个数字时,此逻辑才有效。

答案 3 :(得分:-1)

我尝试了更多并找到了

Math.min(Math.max(数,分钟),最大值);