比较数组中数值的大小是比较常见的操作,比较大小的方法有多种,比如可以使用自带的sort()函数,代码如下:
<html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,minimal-ui"> <title>document</title> </head> <body> <input type="number" id="text" value=""> <input type="button" id="btn" value="提交"> </body> <script> var text = document.getElementById("text"); var btn = document.getElementById("btn"); btn.onclick = function(){ var v = text.value; spl(v); }; function spl(num){ var str = num.split(""); str.sort(func); //排序 function func(i, j){ return i-j; } // var max = parseInt(str[str.length-1]); //方法一:将数组中的字符转成整型 // var min = parseInt(str[0]); var max = str[str.length-1]; //方法二:获取到最大值最小值的字符,然后把计算表达式转成字符串 var min = str[0]; var m = eval(max+"-"+min); //eval方法计算字符串形式的表达式 var n = eval(max+"+"+min); console.log(max+"-"+min+"="+m+";"+max+"+"+min+"="+n); } </script> </html>
另外的求最大值方法如下:
方法一:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
//最小值Array.prototype.min = function() {var min = this[0];var len = this.length;for (var i = 1; i < len; i++){ if (this[i] < min){ min = this[i]; } } return min;}//最大值Array.prototype.max = function() { var max = this[0];var len = this.length; for (var i = 1; i < len; i++){ if (this[i] > max) { max = this[i]; } } return max;} |
如果你是引入类库进行开发,害怕类库也实现了同名的原型方法,可以在生成函数之前进行重名判断:
|
1
2
3
4
5
|
if (typeof Array.prototype['max'] == 'undefined') { Array.prototype.max = function() { ... ...}} |
方法二:
用Math.max和Math.min方法可以迅速得到结果。apply能让一个方法指定调用对象与传入参数,并且传入参数是以数组形式组织的。恰恰现在有一个方法叫Math.max,调用对象为Math,与多个参数
|
1
2
3
4
5
6
|
Array.max = function( array ){ return Math.max.apply( Math, array );};Array.min = function( array ){ return Math.min.apply( Math, array );}; |
但是,John Resig是把它们做成Math对象的静态方法,不能使用大神最爱用的链式调用了。但这方法还能更精简一些,不要忘记,Math对象也是一个对象,我们用对象的字面量来写,又可以省几个比特了。
|
1
2
3
4
5
6
7
8
|
Array.prototype.max = function(){ return Math.max.apply({},this) } Array.prototype.min = function(){ return Math.min.apply({},this) } [1,2,3].max()// => 3 [1,2,3].min()// => 1 |
方法三:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
function getMaximin(arr,maximin) { if(maximin=="max") { return Math.max.apply(Math,arr); }else if(maximin=="min") { return Math.min.apply(Math, arr); } } var a=[3,2,4,2,10]; var b=[12,4,45,786,9,78]; console.log(getMaximin(a,"max"));//10console.log(getMaximin(b,"min"));//04 |
方法四:
|
1
2
3
|
var a=[1,2,3,5];alert(Math.max.apply(null, a));//最大值alert(Math.min.apply(null, a));//最小值 |
多维数组可以这么修改:
|
1
2
3
4
|
var a=[1,2,3,[5,6],[1,4,8]];var ta=a.join(",").split(",");//转化为一维数组alert(Math.max.apply(null,ta));//最大值alert(Math.min.apply(null,ta));//最小值 |
posted on
浙公网安备 33010602011771号