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


基础教程推荐
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01