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

帅比萌擦擦* 提交于 2019-12-01 00:23:30

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

Below is a code that improves the solution and facilitates global use:

/* 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());

OK, let's see how we can make a short function using ES6...

You have this string-number:

const num = "1 2 3 4 5";

and you create a function like this in ES6:

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

and use it like this:

highestAndLowest("1 2 3 4 5"); //return "5 1"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!