返回带空格的数字字符串中的最高和最低数字 [英] Return highest and lowest number in a string of numbers with spaces
本文介绍了返回带空格的数字字符串中的最高和最低数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比方说,我有一串数字,用空格分隔,我想返回最高和最低的数字.如何在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.
这是我到目前为止所拥有的:
Here is what I have so far:
function myFunction(str) {
var tst = str.split(" ");
return tst.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"))
这篇关于返回带空格的数字字符串中的最高和最低数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文