代码片段收集
else-if
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function customerValidation(customer) { if (!customer.email) { return error('email is require') } else if (!customer.login) { return error('login is required') } else if (!customer.name) { return error('name is required') } else { return customer } }
const customerValidation = customer => !customer.email ? error('email is required') : !customer.login ? error('login is required') : !customer.name ? error('name is required') : customer
|
利用arguments
from: Interviewing a front-end developer:
实现log函数
输出参数的值:
log('hello');
// hello
log('hello', 'world');
// hello world
输出自定义字符串+参数:
logWith('hello', 'world');
// (app) hello world
兼容bind
1 2 3 4 5 6
| Function.prototype.bind = Function.prototype.bind || function(context) { var self = this; return function(){ return self.apply(context, arguments); }; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| 'touchstart': 'handleTouchStart', 'touchmove': 'handleTouchMove', 'touchend': 'handleTouchEnd', handleTouchStart: function(event) { this.startClientY = event.touches[0].clientY this.startScrollTop = _scroll_dom.scrollTop() }, handleTouchMove: function(event) { this.currentClientY = event.touches[0].clientY this.currentScrollTop = _scroll_dom.scrollTop() clearTimeout(this.touchTimer) this.touchTimer = setTimeout(function() { self.handleTouchEnd() }, 5) }, handleTouchEnd: function() { clearTimeout(this.touchTimer) var isSwipeUp = this.currentClientY < this.startClientY var isNoScroll = this.currentScrollTop === this.startScrollTop if (isSwipeUp && isNoScroll) { doSomething() } }
|
从 url 中获取参数值
1 2 3
| function getUrlParam(name) { return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null; }
|