JavaScript通过原型给数组添加更多的方法

一、数组获取最大值的方法

     var arr = ["nba","haha","cba","aaa","sbc"];

        Array.prototype.getMax = function(){

    

          var temp = 0;

          for(var x=1; x<this.length; x++){

              if(this[x]>this[temp]){

                  temp = x;

              }

          }

          return this[temp];

      }

    alert(arr.getMax());//以上的this都表示arr这个数组,那个对象调用这个方法this就表示谁

 

 

 

二、数组的字符串表现形式,定义toString方法。 相当于java中的复写。

Array.prototype.toString = function(){

    return "["+this.join("/ ")+"]";

}

var arr=[32,23,32,34322,3232,2453];

alert(arr.toString());

 

你可能感兴趣的:(JavaScript)