一、数组去重
ES6写法:
1、set 、Array.from
var arr = [1,2,22,22,3,4,5,5,6]
var set = new Set(arr) //{1,2,3,4,6}
var setArr = Array.from(set) //讲set结构转为数组array
console.log(setArr) //[1,2,3,4,6]
2、...(拓展运算符) + set
var arr = [1,1,2,3,4]
var tt = [...new Set(arr)]
console.log(tt) //[1,2,3,4]
ES5写法:
var arr = [1,2,3,3,4,4,4,5]
var temObj = {}
var result = []
arr.forEach(function(a){
var key = (typeof a) + a;
if(!temObj[key]){
temObj[key] = true;
result.push(a)
}
})
console.log(result)
二、时间戳转换为日期
var t = 1521694261;
timestampToTime(t);
function timestampToTime(timestamp){
var date = new Date(timestamp * 1000); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
year = date.getFullyear();
month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
day = change(date.getDate());
hour = change(date.getHours());
minute = change(date.getMinutes());
second = change(date.getSeconds());
var times = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
console.log(times)
}
function change(t){
if(t < 10){
return "0" + t
}else{
return t
}
}
三、js千位分割符
var separator = (num) => {
if(!num){
return '0.00';
}
let str = parseFloat(num).toFixed(2);
return str && str
.toString()
.replace(/(d)(?=(d{3})+.)/g, function($0, $1) {
return $1 + ",";
})
}
separator(386485473.88) //"386,485,473.88"