JavaScript常用方法

1、用reduce计算数组的和

function sum(arr) {  
  return arr.reduce(function(prev, curr) {
    return prev + curr;
  });
};

2、计算平均数(Calculator.average(3,4,5) 返回 4)

var Calculator = {  
  average: function() {
    var sum = [].reduce.call(arguments, function(t, n) {
      return t + n;
    }, 0);
    return sum === 0 ? 0 : sum / arguments.length;
  }
};

3、将数组中的非数字过滤(filter_list([1,2,'aasf','1','123',123]) \=\= [1,2,123])

function filter_list(l) {  
  return l.filter(function(v) {
    return typeof v == 'number'
  })
}

4、将键值对的对象转化为“=”号相连的字符串(solution({a: 1, b: '2'}) // 返回 "a = 1,b = 2")

function solution(pairs){  
  return Object.keys(pairs)
    .map(function(k) { return k + ' = ' + pairs[k] })
    .join(',');
}

5、转数字转换为排名(0=>0, 1=>1st, 2=>2nd, 3=>3rd, 11=>11th, 12=>12th, 13=>13th, 21=>21st, 32=>32nd, 111=>111st, 132=>132nd)

function numberToOrdinal(n) {  
  var e = ['th','st','nd','rd','th'];
  return n ?
    n + e[
               n % 100 > 10 && n % 100 < 20
               ? 0
               : Math.min(n % 10 ,4)
            ] : "0"
}

function numberToOrdinal(n) {  
  var suffix = "th";
  if (n == 0) suffix = "";
  if (n % 10 == 1 && n % 100 != 11) suffix = "st";
  if (n % 10 == 2 && n % 100 != 12) suffix = "nd";
  if (n % 10 == 3 && n % 100 != 13) suffix = "rd";
  return n + suffix;
}