美文网首页
js获取平均数

js获取平均数

作者: loser_b45d | 来源:发表于2019-03-05 18:09 被阅读0次

/*

    去掉最大值和最小值,求平均数

    */

    //第一种方法

    function avgFn1(){

      //由于argument是是类数组,不能使用Array.prototype上面的方法

      //1.将类数组转化为数组

      let arr = Array.prototype.slice.call(arguments);

      //或者

      // let arr = [].slice.call(arguments);

      arr.sort((a,b)=>{

        return a - b;

      });

      arr.shift();

      arr.pop();

      return (eval(arr.join("+"))/arr.length).toFixed(2);

    }

    //第二种方法全部借用数组方法

    function avgFn2(){

      Array.prototype.sort.call(arguments,(a,b)=>{

        return a-b;

      });

      [].shift.call(arguments);

      [].pop.call(arguments);

      return (eval([].join.call(arguments,"+"))/arguments.length).toFixed(2);

    }

    let res1 = avgFn1(4,6,2,7,23,63,456,67);

    let res2 = avgFn2(4,6,2,7,23,63,456,67);

    console.log(res1);

    console.log(res2);

相关文章

网友评论

      本文标题:js获取平均数

      本文链接:https://www.haomeiwen.com/subject/puwouqtx.html