var arr=[1,2,3,4,5,6,7];
想获取arr的最大最小值,通常情况下对一个数组的取值 (max ,min)偶尔会用到,最先想到的是数组的每一个值来比较,循环,既麻烦然而自己写的也不怎么对头,那么有什么简单的方法可以获取的呢。
看了下Math这个函数居然有max 和min方法,那么我们怎么用呢 ,对原型数组Array进行一个扩展:
Array.prototype.max=function(){
return Math.max.apply({},this);
}
Array.prototype.min=function(){
return Math.min.apply({},this);
}
经过对原型数组的扩展arr也有了max()和min();
arr.max() 得到数组的最大值,arr.min()得到数组的最小值;
补充一下对于多个数组合并的问题:
var a1=[1,2,3],a2=['a','b','c'];
我们期望得到的是:[1,2,3,'a','b','c'];
Array.prototype.push.apply(a1,a2);即可得到a1=[1,2,3,'a','b','c'];
对于多个数组合并我是这样想的:
Array.prototype.Push=function(){
var contactArray=[];
for(var i=0;i<arguments.length;i++){
Array.prototype.push.apply(contactArray,arguments[i]);
}
return contactArray;
}
我们想得到我们希望的数组var newA=[];newA=newA.Push(a1,a2,a3);newA 就是我们想要的合并数组;
注:argument不是一个数组,它是一个类似数组的对象,希望对大家有所帮助。