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.
这是我目前所拥有的:
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"))
这篇关于返回带有空格的数字字符串中的最高和最低数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回带有空格的数字字符串中的最高和最低数字


- Fetch API 如何获取响应体? 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06