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

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

本文关键字:数字 数字字符 空格 返回 字符串      更新时间:2023-09-26

假设我有一串用空格分隔的数字,我想返回最高和最低的数字。如何使用函数在JS中最好地完成此操作?例:

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

我希望两个数字都以字符串形式返回。最低数字后跟空格,然后是最高数字。

这是我到目前为止所拥有的:

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

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

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

下面是改进解决方案并促进全局使用的代码:

/* Improve the prototype of Array. */
// Max function.
Array.prototype.max = function() {
  return Math.max.apply(null, this);
};
// Min function.
Array.prototype.min = function() {
  return Math.min.apply(null, this);
};
var stringNumbers = "1 2 3 4 5";
// Convert to array with the numbers.
var arrayNumbers = stringNumbers.split(" ");
// Show the highest and lowest numbers.
alert("Highest number: " + arrayNumbers.max() + "'n Lowest number: " + arrayNumbers.min());

好的,让我们看看如何使用 ES6 创建一个简短的函数......

你有这个字符串编号:

const num = "1 2 3 4 5";

你在 ES6 中创建了一个这样的函数:

const highestAndLowest = nums => {
  nums = nums.split(" ");
  return `${Math.max(...nums)} ${Math.min(...nums)}`;
}

并像这样使用它:

highestAndLowest("1 2 3 4 5"); //return "5 1"
function highAndLow(numbers){
  var temp = numbers.split(' ');
  temp.sort(function(a,b){return a-b; });
  return  temp[temp.length-1] + ' ' + temp[0];
}

做了一点不同:首先拆分成一个数组,然后排序...并返回带有第一个(最小)元素的最后一个(最大)元素