【js小技巧(2)】前端小菜也想来日更

73 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第2天,点击查看活动详情

JavaScript 的逗号操作符

JavaScript 里面, , 逗号操作符允许你在同一个地方放多个语句。例如:

    for(var i=0, j=0; i<3; i++, j++, j++){
        console.log(`i: ${i}, j: ${j}`);
    }
    // 输出:
    // i: 0, j: 0
    // i: 1, j: 2
    // i: 2, j: 4

当放一个表达式时,它由左到右计算每个表达式,并传回最右边的表达式。例如:

    function a(){console.log('a'); return 'a';}
    function b(){console.log('b'); return 'b';}
    function c(){console.log('c'); return 'c';}
    var x = (a(), b(), c());
    console.log(x);
    // 输出
    // a
    // b
    // c
    // c (x的值)

注意,, 逗号操作符在 JavaScript 里面中所有的操作符里是最低的优先顺序,所以没有括号表达式将变为:

    x = a(), b(), c();
    console.log(x);
    // 输出
    // a
    // b
    // c
    // a (x的值)

用数组建立一个简单的循环

在一些业务场景,我们需要不断的循环数组的元素,比如音乐播放列表,现在分享一个很简单方案:

    ```
    var aList = ['A','B','C','D','E'];

    function make_looper( arr ) {

        arr.loop_idx = 0;

        // 返回当前的元素
        arr.current = function(){
          if( this.loop_idx < 0 ){
            this.loop_idx = this.length - 1;
          }
          if( this.loop_idx >= this.length ){
            this.loop_idx = 0;
          }
          return arr[ this.loop_idx ];
        };
        
        // 增加 loop_idx 然后返回新的当前元素
        arr.next = function(){
          this.loop_idx++;
          return this.current();
        };
        
        // 减少 loop_idx 然后返回新的当前元素
        arr.prev = function(){
          this.loop_idx--;
          return this.current();
        };
    }

    make_looper( aList);

    aList.current(); // A
    aList.next(); // B
    aList.next(); // C
    aList.next(); // D
    aList.next(); // E
    aList.next(); // A
    aList.pop() ; //  E
    aList.prev(); // D
    aList.prev(); // C
    aList.prev(); // B
    aList.prev(); // A
    aList.prev(); // D

小技巧:使用 % 取模操作符可以使上面的函数变得更优雅哦。%返回除法的余数(1 % 5 // 1; 5 % 5 // 0;)。改进后:

    ```
    function make_looper( arr ){

        arr.loop_idx = 0;

        // 返回当前的元素
        arr.current = function(){
          // 无需判断loop_idx小于0或者大于arr.length
          this.loop_idx = ( this.loop_idx ) % this.length;
          return arr[ this.loop_idx ];
        };

        // 增加 loop_idx 然后返回新的当前元素
        arr.next = function(){
          this.loop_idx++;
          return this.current();
        };

        // 减少 loop_idx 然后返回新的当前元素
        arr.prev = function(){
          this.loop_idx += this.length - 1;
          return this.current();
        };
    }

函数中如何使用可选参数

JavaScript 在一些方法的调用的时候,我们有的参数可传可不传,如果确保函数的正常运行(实例函数中第2个与第3个参数为可选参数):

    function example( err, optionalA, optionalB, callback ) {
        // 使用数组取出arguments
        var args = new Array(arguments.length);
        for(var i = 0; i < args.length; ++i) {
            args[i] = arguments[i];
        };
        
        // 第一个参数为错误参数
        // shift() 移除数组中第一个参数并将其返回
        err = args.shift();

        // 如果最后一个参数是函数,则它为回调函数
        // pop() 移除数组中最后一个参数并将其返回
        if (typeof args[args.length-1] === 'function') { 
            callback = args.pop();
        }
        
        // 如果args中仍有元素,那就是你需要的可选参数
        // 你可以像这样一个一个的将其取出:
        if (args.length > 0) optionalA = args.shift(); else optionalA = null;
        if (args.length > 0) optionalB = args.shift(); else optionalB = null;

        // 像正常一样继续:检查是否有错误
        if (err) { 
            return callback && callback(err);
        }
        
        // 为了教程目的,打印可选参数
        console.log('optionalA:', optionalA);
        console.log('optionalB:', optionalB);
        console.log('callback:', callback);

        /* 你想做的逻辑 */

    }

    // ES6语法书写更简短
    function example(...args) {
        // 第一个参数为错误参数
        const err = args.shift();
        // 如果最后一个参数是函数,则它为回调函数
        const callback = (typeof args[args.length-1] === 'function') ? args.pop() : null;

        // 如果args中仍有元素,那就是你需要的可选参数你可以像这样一个一个的将其取出:
        const optionalA = (args.length > 0) ? args.shift() : null;
        const optionalB = (args.length > 0) ? args.shift() : null;
        // ... 重复取更多参数

        if (err && callback) return callback(err);

        /* 你想做的逻辑 */
    }

    // 使用或不使用可选参数调用实例函数
    example(null, 'AA');
    example(null, function (err) {   /* do something */    });
    example(null, 'AA', function (err) {});
    example(null, 'AAAA', 'BBBB', function (err) {});