有没有好的 JS 速记参考?

发布于 2024-09-26 19:34:03 字数 144 浏览 9 评论 0原文

我希望将任何速记技术融入我的常规编码习惯中,并且当我在紧凑的代码中看到它们时也能够阅读它们。

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

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

I'd like to incorporate whatever shorthand techniques there are in my regular coding habits and also be able to read them when I see them in compacted code.

Anybody know of a reference page or documentation that outlines techniques?

Edit: I had previously mentioned minifiers and it is now clear to me that minifying and efficient JS-typing techniques are two almost-totally-separate concepts.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

南七夏 2024-10-03 19:34:03

已更新,添加了 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
}

关于类型的最后说明

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

Updated with ECMAScript 2015 (ES6) goodies. See at the bottom.

The most common conditional shorthands are:

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

Object literal notation for creating Objects and Arrays:

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

Built in types (numbers, strings, dates, booleans)

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

Variable declaration:

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

String's character at index:

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

ECMAScript 2015 (ES6) standard shorthands

These are relatively new additions so don't expect wide support among browsers.
They may be supported by modern environments (e.g.: newer node.js) or through transpilers. The "old" versions will continue to work of course.

Arrow functions

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

Rest parameters

// 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
}

Default parameter values

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

Destructuring

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

Method definition inside object literals

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

Computed property names inside object literals

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

Bonus: new methods on built-in objects

// 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 

Bonus 2: arrow functions also make self = this capturing unnecessary

// 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
}

Final note about types

Be careful using implicit & hidden type casting and rounding as it can lead to less readable code and some of them aren't welcome by modern Javascript style guides.
But even those more obscure ones are helpful to understand other people's code, reading minimized code.

花开浅夏 2024-10-03 19:34:03

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


表达式闭包:

JavaScript 1.7 及更早版本:

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

JavaScript 1.8 添加了简写 Lambda 表示法,用于使用 表达式闭包

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 中,您可以使用 解构赋值,例如,交换值以避免临时变量:

var a = 1;  
var b = 3;  

[a, b] = [b, a]; 

数组推导式和 filter() 方法:

< JavaScript 1.7 中引入了 a href="https://developer.mozilla.org/en/JavaScript/Guide/Predefined_Core_Objects#Array_compressiveons">数组推导式,它可以减少以下代码:

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)];

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

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

If by JavaScript you also include versions newer than version 1.5, then you could also see the following:


Expression closures:

JavaScript 1.7 and older:

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

JavaScript 1.8 added a shorthand Lambda notation for writing simple functions with expression closures:

var square = function(x) x * x;

reduce() method:

JavaScript 1.8 also introduces the reduce() method to Arrays:

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

Destructuring assignment:

In JavaScript 1.7, you can use the destructuring assignment, for example, to swap values avoiding temporary variables:

var a = 1;  
var b = 3;  

[a, b] = [b, a]; 

Array Comprehensions and the filter() method:

Array Comprehensions were introduced in JavaScript 1.7 which can reduce the following code:

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]);
  }
}

To something like this:

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

Or using the filter() method in Arrays which was introduced in JavaScript 1.6:

var numbers = [1, 2, 3, 21, 22, 30];
var evens = numbers.filter(function(i) { return i % 2 === 0; });  
唔猫 2024-10-03 19:34:03

您正在寻找 JavaScript 语言的习语

看看 JavaScript 1.6+ 中的新功能确实很有趣,但你不知道由于缺乏主流支持,将能够在野外使用语言功能(例如,列表推导式或 yield 关键字)。然而,如果您还没有接触过 Lisp 或 Scheme,那么学习新的标准库函数是值得的。许多典型的函数式编程,例如 mapreducefilter 很值得了解,并且经常出现在 jQuery 等 JavaScript 库中;另一个有用的函数是 bind (代理 在 jQuery 中,在一定程度上),这在将方法指定为回调时很有帮助。

You're looking for idioms of the JavaScript language.

It's certainly interesting to peek at what's new in JavaScript 1.6+ but you're not going to be able to use the language features (e.g., list comprehensions or the yield keyword) in the wild due to lack of mainstream support. It is worthwhile to learn about new standard library functions if you haven't had exposure to Lisp or Scheme, however. Many typical pieces of functional programming such as map, reduce, and filter are good to know and often show up in JavaScript libraries like jQuery; another useful function is bind (proxy in jQuery, to an extent), which is helpful when specifying methods as callbacks.

云仙小弟 2024-10-03 19:34:03

获取数组的最后一个值

这并不是真正的简写,而更像是大多数人使用的技术的更短的替代技术

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

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

< 的部分code>.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 并按 Enter 键。它很可能会返回

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

Getting the last value of an array

This is not really a shorthand, but more like a shorter alternative technique to the technique most people use

When I need to get the last value of an array, I usually use the following technique:

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

The part of .slice(-1)[0] being the shorthand technique. This is shorter compared to the method I've seen almost everyone else use:

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

Testing this shorthand's relative computing speed

To test this, I did the following:

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');

And then seperately (to prevent possible synchronous running):

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 results:

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

Conclusion: No disadvantages in using this shorthand.

Debugging shorthands

Most browsers do support hidden global variables for every element with an id. So, if I need to debug something, I usually just add a simple id to the element and then use my console to access it via the global variable. You can check this one yourself: Just open your console right here, type footer and press enter. It will most likely return the <div id="footer> unless you've got that rare browser that doesn't have this (I haven't found any).

If the global variable is already taken up by some other variable I usually use the horrible document.all['idName'] or document.all.idName. I am of course aware this is terribly outdated, and I don't use it in any of my actual scripts, but I do use it when I don't really want to type out the full document.getElementById('idName') since most browsers support it anyway, Yes I am indeed quite lazy.

江南烟雨〆相思醉 2024-10-03 19:34:03

这个 github 存储库致力于 Javascript 的字节节省技术。我觉得非常方便!

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

This github repo is dedicated to byte-saving techniques for Javascript. I find it quite handy!

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文