zoukankan      html  css  js  c++  java
  • 25.获取平均数

    求平均数,去除一个最高分,去除一个最低分

    方法一:

    // argument是一个类数组集合,它不是数组,不能直接使用数组的方法

    function avgFn () {

      var ary = [];

      for (var i = 0; i<arguments.length; i++) {

        console.log()

        ary[ary.length] = arguments[i]

      }

      ary.sort(function(a,b) {

        return a-b;

      })

      ary.shift()

      ary.pop()

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

    }

    var res = avgFn(9.8, 9.7, 10 ,9.9, 9.0, 9.8, 3.0);

    console.log(res)

    方法二:借用数组原型上的slice方法,当slice执行的时候,让方法中的this变为我要处理的arguments,实现将类数组arguments转换为数组

    function argFn () {

      var ary = [].slice.call(arguments)

      ary.sort(function(a,b) {

        return a-b;

      })

      ary.shift()

      ary.pop()

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

    }

    var res = avgFn(9.8, 9.7, 10 ,9.9, 9.0, 9.8, 3.0);

    console.log(res)

    方法三:通过改变this指向

    function argFn () {

      [].sort.call(arguments,function (a,b) {

        return a-b;

      });

      [].shift.call(arguments);

      [].pop.call(arguments);

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

    }

    var res = avgFn(9.8, 9.7, 10 ,9.9, 9.0, 9.8, 3.0);

    console.log(res)

  • 相关阅读:
    微信朋友圈分享链接的【图片】设置
    Apache无法访问 Forbidden
    Chrome不能登录和同步的解决方法
    为js和css文件自动添加版本号
    Sqlserver替换函数Replace
    javascript 回车提交指定按钮
    ★★★.NET 在meta标签中使用表达式设置页面的关键字
    es6对象扩展
    es6数组新方法
    es6 字符串
  • 原文地址:https://www.cnblogs.com/z-dl/p/8961091.html
Copyright © 2011-2022 走看看