别人家的代码

来源:互联网 发布:淘宝官网首页登录 编辑:程序博客网 时间:2024/06/12 01:06

数字补0、年份位数——巧用substr

art template helper

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)
0 0