今日份痛苦与一些js片段记录
续:
一段让我抓狂了一个小时的js代码....
/* 注释这个函数,正常 */
Array.prototype.MyForEach = function (cb) {
console.log("this inner:", this);
for (let i = 0, len = this.length; i < len; i++ ) {
console.log("loop_inner");
cb(this[i]);
}
}
// const arr = new Array(1, 2, 3, 4);
/* 这里的注释打开也正常 */
// const arr = [1, 2, 3, 4];
// arr.MyForEach(function (v) {
// console.log(v);
// console.log('loop');
// });
[1,2,3].forEach(v=>console.log(v))
输出是:
TypeError: Cannot read property 'forEach' of undefined
神奇的是:注释掉顶部的函数就正常...
后面才想到,是不是顶部增加了Array
的prototype
,所以就node
解析的时候就字面量的prototype
被冻结了???,感觉似乎有一点点道理,到浏览器中跑也是这样报错,说明是v8引擎吗?
再突然不知怎么操作的,发现...正常了???
原来是函数声明后没加逗号,散了散了...(都怪eslint
设置的不需逗号的习惯惹的粗啊....)
js片段记录
记录一些好用的js片段:
js 获取当前月的开始第一天和最后一天
initTimeThisMonth() {
const year = new Date().getFullYear()
const month = this.toDouble(new Date().getMonth() + 1)
const day_end = this.getCountDays()
const day_start = '01'
const beginDate = `${year}-${month}-${day_start}`
const endDate = `${year}-${month}-${day_end}`
return {
beginDate: beginDate,
endDate: endDate
}
},
getCountDays() {
const curDate = new Date()
curDate.setMonth(curDate.getMonth() + 1)
// setDate: 如果参数指定0,那么日期就会被设置为上个月的最后一天
curDate.setDate(0)
return curDate.getDate()
}
主要的trick的地方就是怎么获取当前如果 dayValue 超出了月份的合理范围,setDate 将会相应地更新 Date 对象。例如,如果为 dayValue 指定0,那么日期就会被设置为上个月的最后一天月的最后一天,因为有的是30,有的是31,而且还有2月的平闰年,第一反应会是利用一个const数组来存储这些月,但是直接搜了一波,发现了这个trick的方法
可以参看mdn的解释: [Date.prototype.setDate()
](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate)
语法:
dateObj.setDate(dayValue)
dayValue
:一个整数,表示该月的第几天如果 dayValue 超出了月份的合理范围,setDate 将会相应地更新 Date 对象。例如,如果为 dayValue 指定0,那么日期就会被设置为上个月的最后一天
js 遇到ie中不能new Date("xxxx-xx-xx")的问题
if (date.length > 12) {
const a = date.split(' ')
const d = a[0].split('-')
const t = a[1].split(':')
date = new Date(d[0], (d[1] - 1), d[2], t[0], t[1], t[2])
} else {
const d = date.trim().split('-')
date = new Date(d[0], (d[1] - 1), d[2])
}