一些javascript常用方法

时间:2023-12-25 10:11:13

1、输入一个正整数n,从1累加到n,返回结果。(如果输入为非正整数,如:小数、0、负数、NaN或其它非数字则返回false)

function f(n){
return ~~+n == n && n > 0 ? n * ++n / 2 : false;
}

2、用reduce计算数组的和

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

3、计算平均数(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;
}
};

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

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

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

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

6、转数字转换为排名(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;
}