妙用隐式转换
字符串转number:
// 字符串转number
+'123'
new Date转时间戳:
// new Date转时间戳
+new Date()
数组/多维数组转为逗号分割字符串(可用于多维数组转一维):
//数组/多维数组转为逗号分隔字符串(可用于多维数组转一维)
''+[1,2,3,[6,7,8]]
解构:
互相交换a,b的值:
var a=1;
var b=2;
// 互相交换a,b的值
[a,b] = [b,a];
console.log(a,b);
扩展运算符:
取数组最大值/最小值:
Math.max(...[1,2,3]);
Math.min(...[1,2,3]);
生成时间:
new Date(...[2019,9,26]);
合并对象:
let obj1 = {a:1, b:2};
let obj2 = {b:3, c:4};
let a = {...obj1, ...obj2}
// 等同于
Object.assign(obj1,obj2);
常用方法:
数字前补0:
function preFixNum(num, length){
return (Array(length).join('0') + num).slice(-length);
}
数组元素为对象的去重:
[...new Set(arr.map(v => JSON.stringify(v)))].map(v => JSON.parse(v));
数组求和:
var arr = [1,2,3,4];
// method 1:
var sum = eval(arr.join('+'));
// mehtod 2:
var sum = arr.reduce((prev,cur) => prev + cur);
金钱格式化(千分):
let money = 11111;
// method 1:
money.toLocaleString('en-US');
// method 2:
Intl.NumberFormat().format(money);
// method 3:
String(money).replace(/\B(?=(\d{3}+(?!\d))/g,',');