1. 如何判断Date对象是一个有效的Date对象
var d = new Date("foo"); console.log(d.toString()); // shows 'Invalid Date' console.log(typeof d); // shows 'object' console.log(d instanceof Date); // shows 'true'
该问题来源于Stack Overflow,地址:
https://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript/12372720#12372720
其实只要简单的判断 date.getTime() === date.getTime() 就行,因为 NaN 不等于 NaN
2. 突破定时器的限制
setTimeout 及 setInterval 里面针对第二个毫秒参数是有上限限制的,最大只能到2^31-1 毫秒,也就是24.8天,超过该数值造成溢出,函数会立即执行。所以在实际情况中出现需要长时间延时/重复,那么就需要引入 long-timeout
https://www.npmjs.com/package/long-timeout
而node-schedule 的定期执行正是基于此
那么long-timeout是怎么做的呢?
其实很简单,核心代码如下:
Timeout.prototype.start = function() { if (this.after <= TIMEOUT_MAX) { this.timeout = setTimeout(this.listener, this.after) } else { var self = this this.timeout = setTimeout(function() { self.after -= TIMEOUT_MAX self.start() }, TIMEOUT_MAX) } if (this.unreffed) { this.timeout.unref() } }
超过了就递归调用就是
3. html 字符转义的科学写法
为了防止xss攻击,需要对字符中的 < > " ' & 字符进行转义,有时候我们为了方便,用正则
a.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
这种形式对字符串进行替换,这种写法对短字符串可能无所谓,但是如果是长字符串呢?还要正则全局匹配?
所以需要我们对字符串进行最少次数的操作进行字符替换
正好看了npm escape-html 的源码,简言之就是通过match /["'&<>]/ 正则,得到匹配到的字符的类数组
然后forEach,替换拼接,效率得到了提升
1 var matchHtmlRegExp = /["'&<>]/; 2 function escapeHtml(string) { 3 var str = '' + string; 4 var match = matchHtmlRegExp.exec(str); 5 6 if (!match) { 7 return str; 8 } 9 10 var escape; 11 var html = ''; 12 var index = 0; 13 var lastIndex = 0; 14 15 for (index = match.index; index < str.length; index++) { 16 switch (str.charCodeAt(index)) { 17 case 34: // " 18 escape = '"'; 19 break; 20 case 38: // & 21 escape = '&'; 22 break; 23 case 39: // ' 24 escape = '''; 25 break; 26 case 60: // < 27 escape = '<'; 28 break; 29 case 62: // > 30 escape = '>'; 31 break; 32 default: 33 continue; 34 } 35 36 if (lastIndex !== index) { 37 html += str.substring(lastIndex, index); 38 } 39 40 lastIndex = index + 1; 41 html += escape; 42 } 43 44 return lastIndex !== index 45 ? html + str.substring(lastIndex, index) 46 : html; 47 }