本文介绍了返回带有空格的数字字符串中的最高和最低数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
假设我有一串用空格分隔的数字,我想返回最高和最低的数字.如何在 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"))
这篇关于返回带有空格的数字字符串中的最高和最低数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)