【问题标题】:Is there a good JS shorthand reference out there?那里有很好的 JS 速记参考吗?
【发布时间】:2011-04-23 09:43:52
【问题描述】:

我想在我的常规编码习惯中加入任何速记技术,并且当我在压缩代码中看到它们时也能够阅读它们。

有人知道概述技术的参考页面或文档吗?

编辑:我之前提到过缩小器,现在我很清楚缩小和高效的 JS 打字技术是两个几乎完全不同的概念。

【问题讨论】:

    标签: javascript shorthand


    【解决方案1】:

    更新 ECMAScript 2015 (ES6) 好东西。见底部。

    最常见的条件简写是:

    a = a || b     // if a is falsy use b as default
    a || (a = b)   // another version of assigning a default value
    a = b ? c : d  // if b then c else d
    a != null      // same as: (a !== null && a !== undefined) , but `a` has to be defined
    

    用于创建对象和数组的对象字面量表示法:

    obj = {
       prop1: 5,
       prop2: function () { ... },
       ...
    }
    arr = [1, 2, 3, "four", ...]
    
    a = {}     // instead of new Object()
    b = []     // instead of new Array()
    c = /.../  // instead of new RegExp()
    

    内置类型(数字、字符串、日期、布尔值)

    // Increment/Decrement/Multiply/Divide
    a += 5  // same as: a = a + 5
    a++     // same as: a = a + 1
    
    // Number and Date
    a = 15e4        // 150000
    a = ~~b         // Math.floor(b) if b is always positive
    a = b**3        // b * b * b
    a = +new Date   // new Date().getTime()
    a = Date.now()  // modern, preferred shorthand 
    
    // toString, toNumber, toBoolean
    a = +"5"        // a will be the number five (toNumber)
    a = "" + 5 + 6  // "56" (toString)
    a = !!"exists"  // true (toBoolean)
    

    变量声明:

    var a, b, c // instead of var a; var b; var c;
    

    字符串在索引处的字符:

    "some text"[1] // instead of "some text".charAt(1);
    

    ECMAScript 2015 (ES6) 标准简写

    这些是相对较新的添加,因此不要期望在浏览器中得到广泛支持。 现代环境(例如:较新的 node.js)或转译器可能支持它们。 “旧”版本当然会继续工作。

    箭头函数

    a.map(s => s.length)                    // new
    a.map(function(s) { return s.length })  // old
    

    静止参数

    // new 
    function(a, b, ...args) {
      // ... use args as an array
    }
    
    // old
    function f(a, b){
      var args = Array.prototype.slice.call(arguments, f.length)
      // ... use args as an array
    }
    

    默认参数值

    function f(a, opts={}) { ... }                   // new
    function f(a, opts) { opts = opts || {}; ... }   // old
    

    解构

    var bag = [1, 2, 3]
    var [a, b, c] = bag                     // new  
    var a = bag[0], b = bag[1], c = bag[2]  // old  
    

    对象字面量内的方法定义

    // new                  |        // old
    var obj = {             |        var obj = {
        method() { ... }    |            method: function() { ... }
    };                      |        };
    

    对象字面量内的计算属性名称

    // new                               |      // old
    var obj = {                          |      var obj = { 
        key1: 1,                         |          key1: 5  
        ['key' + 2]() { return 42 }      |      };
    };                                   |      obj['key' + 2] = function () { return 42 } 
    

    奖励:内置对象的新方法

    // convert from array-like to real array
    Array.from(document.querySelectorAll('*'))                   // new
    Array.prototype.slice.call(document.querySelectorAll('*'))   // old
    
    'crazy'.includes('az')         // new
    'crazy'.indexOf('az') != -1    // old
    
    'crazy'.startsWith('cr')       // new (there's also endsWith)
    'crazy'.indexOf('az') == 0     // old
    
    '*'.repeat(n)                  // new
    Array(n+1).join('*')           // old 
    

    奖励 2:箭头函数也使 self = this 无需捕获

    // new (notice the arrow)
    function Timer(){
        this.state = 0;
        setInterval(() => this.state++, 1000); // `this` properly refers to our timer
    }
    
    // old
    function Timer() {
        var self = this; // needed to save a reference to capture `this`
        self.state = 0;
        setInterval(function () { self.state++ }, 1000); // used captured value in functions
    }
    

    关于类型的最后说明

    小心使用隐式和隐藏类型转换和舍入,因为它会导致代码可读性降低,并且其中一些代码不受modern Javascript style guides 的欢迎。 但即使是那些比较晦涩的代码也有助于理解其他人的代码,阅读最小化的代码。

    【讨论】:

    • x && (doWhentrue); if(x) do; 相同
    • 那么毕竟Math.pow(x, 2)这个简写仍然是平方x的最短方法?
    • x*x 是目前最短的方法 :) 现代浏览器正在实现指数运算符(ES7):github.com/rwaldron/exponentiation-operator 所以你可以做x ** 2,对其他指数更有用当然。
    • 注意!使用箭头函数需要注意this在其中不可用。 function () {} 和 () 不一样 => {}
    【解决方案2】:

    如果通过 JavaScript 还包括比 1.5 版更新的版本,那么您还可以看到以下内容:


    表达式闭包:

    JavaScript 1.7 及更早版本:

    var square = function(x) { return x * x; }
    

    JavaScript 1.8 添加了一个简写 Lambda notation 用于使用 expression closures 编写简单的函数:

    var square = function(x) x * x;
    

    reduce() 方法:

    JavaScript 1.8 还向数组引入了reduce() 方法:

    var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });  
    // total == 6 
    

    解构赋值:

    在 JavaScript 1.7 中,您可以使用 destructuring assignment,例如,交换值以避免临时变量:

    var a = 1;  
    var b = 3;  
    
    [a, b] = [b, a]; 
    

    数组理解和 filter() 方法:

    Array Comprehensions 是在 JavaScript 1.7 中引入的,可以减少以下代码:

    var numbers = [1, 2, 3, 21, 22, 30];  
    var evens = [];
    
    for (var i = 0; i < numbers.length; i++) {
      if (numbers[i] % 2 === 0) {
        evens.push(numbers[i]);
      }
    }
    

    这样的:

    var numbers = [1, 2, 3, 21, 22, 30];
    var evens = [i for each(i in numbers) if (i % 2 === 0)];
    

    或者使用 JavaScript 1.6 中引入的数组中的filter() 方法:

    var numbers = [1, 2, 3, 21, 22, 30];
    var evens = numbers.filter(function(i) { return i % 2 === 0; });  
    

    【讨论】:

    • 我认为任何缩小器都不会做这些...... :)
    • @galambalazs:不,我也不这么认为。缩小器这样做是不正确的,因为这样的转换会使代码在支持 JavaScript 1.5 版本的引擎中不兼容......尽管如此,这些仍然是在以后的版本中缩短代码的几个选项,可能更多是出于可读性目的而不是比缩小。
    • @galambalazs:我没有那样解释这个问题:) ... OP 问:“我想在我的常规编码习惯中加入任何速记技术......”
    • +1 JS 1.7 中的数组理解? 我怎么不知道这个?!
    • SyntaxError: Unexpected token for 这是我为每个 bla bla 运行代码时得到的...
    【解决方案3】:

    您正在寻找 JavaScript 语言的习语

    查看what's new in JavaScript 1.6+ 肯定很有趣,但由于缺乏主流支持,您将无法在野外使用语言功能(例如,列表解析或yield 关键字)。但是,如果您没有接触过 Lisp 或 Scheme,那么学习新的标准库函数是值得的。许多典型的函数式编程片段,例如mapreducefilter,都很值得了解,并且经常出现在 jQuery 等 JavaScript 库中;另一个有用的函数是 bind(在一定程度上是 jQuery 中的 proxy),它在将方法指定为回调时很有帮助。

    【讨论】:

      【解决方案4】:

      获取数组的最后一个值

      这并不是真正的速记,而更像是大多数人使用的技术的一种更短的替代技术

      当我需要获取数组的最后一个值时,我通常使用以下技术:

      var str = 'Example string you actually only need the last word of FooBar';
      var lastWord = str.split(' ').slice(-1)[0];
      

      .slice(-1)[0] 的部分是速记技术。与我见过的几乎其他人使用的方法相比,这更短:

      var str = 'Example string you actually only need the last word of FooBar';
      var lastWord = str.split(' ');
          lastWord = lastWord[lastWord.length-1];
      

      测试这个速记的相对计算速度

      为了对此进行测试,我做了以下操作:

      var str = 'Example string you actually only need the last word of FooBar';
      var start = +new Date();
      for (var i=0;i<1000000;i++) {var x=str.split(' ').slice(-1)[0];}
      console.log('The first script took',+new Date() - start,'milliseconds');
      

      然后分开(防止可能的同步运行):

      var start2 = +new Date();
      for (var j=0;j<1000000;j++) {var x=str.split(' ');x=x[x.length-1];}
      console.log('The second script took',+new Date() - start,'milliseconds');
      

      结果:

      The first script took 2231 milliseconds
      The second script took 8565 milliseconds
      

      结论:使用这种速记没有缺点。

      调试速记

      大多数浏览器都支持为每个具有 id 的元素隐藏全局变量。因此,如果我需要调试某些东西,我通常只需向元素添加一个简单的 id,然后使用我的控制台通过全局变量访问它。您可以自己检查一下:只需在此处打开您的控制台,输入footer 并按回车键。它很可能会返回&lt;div id="footer&gt;,除非您拥有没有此功能的稀有浏览器(我还没有找到)。

      如果全局变量已经被其他变量占用,我通常使用 horrible document.all['idName']document.all.idName。我当然知道这是非常过时的,并且我不会在我的任何实际脚本中使用它,但是当我真的不想输入完整的 document.getElementById('idName') 时我会使用它,因为大多数浏览器都支持它,是的,我确实很懒。

      【讨论】:

        【解决方案5】:

        这个 github 存储库专门用于 Javascript 的字节保存技术。我觉得很方便!

        https://github.com/jed/140bytes/wiki/Byte-saving-techniques

        【讨论】:

        • 你成就了我的一天!这个要点很好读,我刚刚学到了很多东西;)
        猜你喜欢
        • 2011-02-20
        • 2010-10-29
        • 1970-01-01
        • 2011-01-16
        • 2011-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-02
        相关资源
        最近更新 更多