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)

  • 相关阅读:
    Duplicate keys detected: '0'. This may cause an update error.
    better-scroll在移动端绑定click事件失效
    vue-awesome-swiper轮播插件的使用方法及问题。
    可运行的js代码
    CSS3表达式calc( )
    webstorm破解教程
    box-decoration-break属性
    shiro自定义密码校验器
    获取select中option被选中的值
    SpringBoot开发验证码功能
  • 原文地址:https://www.cnblogs.com/z-dl/p/8961091.html
Copyright © 2011-2022 走看看