Codewars刷题遭虐之一

题目很简单,不过是求数组平均数而已。但是看了老外写的东西还是觉得三观受了冲击(┐「ε:)

题目如下:

Description:
Given an array of integers, calculate the Average of these numbers.
Main challenge is to write shortest and compact function for it.
For example: var a = [0, 1, 2];
avg(a) // output should be 1
Output of function will be also checked in tests, however most important is to write the shortest possible function as test will check length of written function. Input will always be valid.

我是这么写的:

function avg(a){
      var sum = 0;
      for(var i = 0; i<a.length; i++){
        sum += a[i];
      }
      return sum/a.length
    }

嗯,太简单了,下个题吧。

嗯?????这些老外写的是什么鬼

function avg(a){for(i=j=0;i in a;j+=a[i++]);return j/i}

a[i++]有点意思蛤

let avg = (a) => a.reduce((a, b) => a + b) / a.length;

看这es6!多简洁流畅的reduce! ( _ _)ノ|扶墙

不过看了clever最高的发现我还是弱爆了:

function avg(a){return eval(a.join("+"))/a.length}

。。。。。。

eval还能这么用的!!!(╯‵□′)╯︵┻━┻

我在这条不归路上越走越远了。。。



评论

123

haha

2018-11-13 23:17

在这里输入