Return highest and lowest number in a string of numbers with spaces

后端 未结 4 1906
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 14:14

Let\'s say I have a string of numbers separated by spaces and I want to return the highest and lowest number. How could that best be done in JS using a function? Example:

4条回答
  •  长情又很酷
    2021-01-03 14:46

    You can use Math.min and Math.max, and use them in an array to return the result, try:

    function highestAndLowest(numbers){
      numbers = numbers.split(" ");
      return Math.max.apply(null, numbers) + " " +  Math.min.apply(null, numbers)
    }
    
    document.write(highestAndLowest("1 2 3 4 5"))

提交回复
热议问题