返回带有空格的数字字符串中的最高和最低数字

2022-01-17 00:00:00 numbers javascript

假设我有一串用空格分隔的数字,我想返回最高和最低的数字.如何在 JS 中使用函数最好地做到这一点?示例:

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:

highestAndLowest("1 2 3 4 5"); // return "5 1"

我希望这两个数字都以字符串的形式返回.最小的数字先跟一个空格,然后是最大的数字.

I would like the both numbers to be returned in a string. The lowest number first followed by a space then the highest number.

这是我目前所拥有的:

function myFunction(str) {
    var tst = str.split(" ");
    return tst.max();
}

推荐答案

你可以使用 Math.min 和 Math.max,并在数组中使用它们返回结果,试试:

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"))

相关文章