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


基础教程推荐
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01