数字补0、年份位数——巧用substr
function (date, format) {
date = new Date(date);
var map = {
"M": date.getMonth() + 1, //月份
"d": date.getDate(), //日
"h": date.getHours(), //小时
"m": date.getMinutes(), //分
"s": date.getSeconds(), //秒
"q": Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒
};
format = format.replace(/([yMdhmsqS])+/g, function(all, t){
var v = map[t];
if(v !== undefined){
if(all.length > 1){
/*---------attention----------*/
v = '0' + v;
v = v.substr(v.length-2);
/*---------attention----------*/
}
return v;
}
else if(t === 'y'){
/*---------attention----------*/
return (date.getFullYear() + '').substr(4 - all.length);
/*---------attention----------*/
}
return all;
});
return format;
}
获取动态变化的最新值——用函数返回的形式,而非变量初始值
function Scope(){
this.$$watchers=[]; //监听器
}
Scope.prototype.$watch=function(name,exp,listener){
this.$$watchers.push({
name:name, //数据变量名
last:'', //数据变量旧值
/*---------attention----------*/
newVal:exp, //返回数据变量新值的函数
/*---------attention----------*/
listener:listener || function(){} //监听回调函数,变量“脏”时触发
})
}
var $scope=new Scope();
$scope.name="Lowes";
for(var key in $scope){
//非函数数据才进行绑定
if(key!="$$watchers" && typeof $scope[key]!="function") {
/*---------attention----------*/
$scope.$watch(key, (function (index) {
return function(){
return $scope[index];
}
})(key))
/*---------attention----------*/
}
}
slice将类数组对象转化为数组
function list() {
return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3); // [1, 2, 3]
除了使用 Array.prototype.slice.call(arguments),你也可以简单的使用 [].slice.call(arguments) 来代替。另外,你可以使用 bind 来简化该过程。
var unboundSlice = Array.prototype.slice;
var slice = Function.prototype.call.bind(unboundSlice);
function list() {
return slice(arguments);
}
var list1 = list(1, 2, 3); // [1, 2, 3]
- 为什么直接用
var slice = Array.prototype.slice.call
会报错:Uncaught TypeError: slice is not a function,但是打印typeof slice
=>'function'
?- 猜测:因为
slice
打印出来是call() { [native code] }
,call
函数无法单独使用,必须和function
一起使用。
- 猜测:因为
利用移位判断奇偶
这里写链接内容
偶数:(index & 1) === 0
奇数:(index & 1) === 1
// jQuery
$('selector:even')
// Native
$$('selector').filter((el, index) => (index & 1) === 0)
字符串去重
function textEliminateDuplicationAndSorting(text) {
return text.split('').filter((value, index, self) => {
return self.indexOf(value) === index;
}).sort().join('')
}