纯函数:
- 相同输入总是会返回相同的输出。
- 不产生副作用。
- 不依赖于外部状态。
函数传参:
当一个函数的参数多余两个的时候,应该将参数对象化:
//Badconst exampleFunc = (a,b,c,d) => {//do something you needreturn a + b + c + d;}//when you use this functionexampleFunc(1,3,6,8);//Goodconst exampleFunc = ({num1,num2,num3,num4}) => {return num1 + num2 + num3 + num4;}//when you use this functionexampleFunc({num1:1,num2:23,num3:4,num4:9})
ISO Date在IOS设备和非IOS设备的解析不同
function formatISODate2YMD1(date) {let d = null;if (date) {let fullDateStr = date.split('T')[0];const [year, month, day] = fullDateStr.split('-');return { year, month, day };}return d;}function formatISODate2YMD2(date) {let d = null;if (date) {d = new Date(date);let month = d.getMonth() + 1;let day = d.getDate() > 9 ? d.getDate() : `0${d.getDate()}`;let m = month > 9 ? month : `0${month}`;return { year: d.getFullYear(), month: m, day };}return d;}let formatRes1 = formatISODate2YMD1('2019-04-23T18:36:35.68');let formatRes2 = formatISODate2YMD2('2019-04-23T18:36:35.68');console.log(formatRes1);console.log(formatRes2);
这是在Chrome浏览器内的执行结果,从结果上来说日期方面基本是一致的:

但是在实际的H5运用中,IOS中的表现,方法一和方法二的结果是不同的,这里没有办法实测,就不进行截图了。经查得知,IOS中对ISO日期的解析会比其他设备中多算八个小时,也就是说当参数值的时间在当日的下午16点之后,那么实际解析出来的日期就是下一天的日期值。
这是一个坑。
对象深浅拷贝
//浅拷贝const obj1 = {a:1};const obj2 = obj1;obj2.a = 2;console.log(obj1);//{a:2}console.log(obj2);//{a:2}//深拷贝const obj1 = {a:1}const obj2 = JSON.parse(JSON.stringfy(obj1));obj2.a = 2;console.log(obj1);//{a:1}console.log(obj2);//{a:2}//深拷贝 ES6const obj1 = {a:1};const obj2 = {...obj1};const obj3 = Object.assign({},obj2);obj2.a = 2;obj3.a = 3;console.log(obj1);//{a:1}console.log(obj2);//{a:2}console.log(obj3);//{a:3}
数组交集、并集、差集ES6
var a = [1,2,3,4,5]var b = [2,4,6,8,10]console.log("数组a:", a);console.log("数组b:", b);var sa = new Set(a);var sb = new Set(b);// 交集let intersect = a.filter(x => sb.has(x));// 差集let minus = a.filter(x => !sb.has(x));// 补集let complement = [...a.filter(x => !sb.has(x)), ...b.filter(x => !sa.has(x))];// 并集let unionSet = Array.from(new Set([...a, ...b]));console.log("a与b的交集:", intersect);console.log("a与b的差集:", minus);console.log("a与b的补集:", complement);console.log("a与b的并集:", unionSet);
节流
函数节流 throttle
指定时间间隔内只会执行一次任务 常用于滚动条滚动监听等
function throttle(fn, threshhold) {var timeoutvar start = new Datevar threshhold = threshhold || 160return function () {var context = this, args = arguments,curr = new Date() - 0clearTimeout(timeout)if (curr - start >= threshhold) {fn.apply(context, args) //只执行一部分方法,这些方法是在某个时间段内执行一次start = curr} else {timeout = setTimeout(function () {fn.apply(context, args)}, threshhold)}}}
防抖
任务频繁触发的情况下,只有任务触发的间隔超过指定间隔的时候,任务才会执行
即:用户在不触发事件时,才触发相应动作,以抑制本来在事件中要执行的动作。
常用于用户输入验证等
function debounce(func, delay) {var timeoutreturn function(e) {clearTimeout(timeout)var context = this, args = argumentstimeout = setTimeout(function(){func.apply(context, args)},delay)}}
