返回带空格的数字字符串中的最高和最低数字
Return highest and lowest number in a string of numbers with spaces
假设我有一串用空格分隔的数字,我想返回最高和最低的数字。如何使用函数在JS中最好地完成此操作?例:
highestAndLowest("1 2 3 4 5"); // return "5 1"
我希望两个数字都以字符串形式返回。最低数字后跟空格,然后是最高数字。
这是我到目前为止所拥有的:
function myFunction(str) {
var tst = str.split(" ");
return tst.max();
}
>您可以使用 Math.min 和 Math.max,并在数组中使用它们以返回结果,请尝试:
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"))
下面是改进解决方案并促进全局使用的代码:
/* Improve the prototype of Array. */
// Max function.
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
// Min function.
Array.prototype.min = function() {
return Math.min.apply(null, this);
};
var stringNumbers = "1 2 3 4 5";
// Convert to array with the numbers.
var arrayNumbers = stringNumbers.split(" ");
// Show the highest and lowest numbers.
alert("Highest number: " + arrayNumbers.max() + "'n Lowest number: " + arrayNumbers.min());
好的,让我们看看如何使用 ES6 创建一个简短的函数......
你有这个字符串编号:
const num = "1 2 3 4 5";
你在 ES6 中创建了一个这样的函数:
const highestAndLowest = nums => {
nums = nums.split(" ");
return `${Math.max(...nums)} ${Math.min(...nums)}`;
}
并像这样使用它:
highestAndLowest("1 2 3 4 5"); //return "5 1"
function highAndLow(numbers){
var temp = numbers.split(' ');
temp.sort(function(a,b){return a-b; });
return temp[temp.length-1] + ' ' + temp[0];
}
做了一点不同:首先拆分成一个数组,然后排序...并返回带有第一个(最小)元素的最后一个(最大)元素
相关文章:
- 如何为jQuery屏蔽输入插件创建一个允许字母数字、空格和重音字符的掩码
- 带静态字符e输入的文本框数字和带javascript的负整数
- 使用正则表达式匹配长度为六个字符的字母数字字符串
- 删除图形和数字之间的连字符(-)符号
- 如何限制一个字段只接受4个数字字符作为输入,并获得'It’这是潜水警报
- 为什么这个正则表达式不't匹配最后一个字母数字字符
- PHP 中的 ASCII 数字到字符错误
- 如何防止数字使用数字1“E”数字2
- javascript中不带数字和字符的字符串的正则表达式
- 如何从包含数字和字符的字符串中获取数值
- Regex Javascript(必须有一个数字和字符)
- 用正则表达式获取3后的数字和字符
- 获取匹配字符串后的数字和字符
- Javascript验证字符串是一个后跟数字的字符
- 什么是html模式,允许数字,字符和点在输入字段
- 在文本区域输入数字或字符时,如何减少计数
- 字符串的最小值包含数字、字符和空格
- 我需要让用户输入任何数字和字符,并且只输入'-'或者''在田地里.我该如何用正则表达式做
- 在页面刷新时以正确的数字启动字符计数器
- 输入文本将值转换为整数/数字/数字进行比较