Javascript 有好的JS速记参考吗?
我希望将任何速记技巧融入到我的常规编码习惯中,并且当我在压缩代码中看到它们时,也能够阅读它们 有人知道概述技术的参考页或文档吗Javascript 有好的JS速记参考吗?,javascript,shorthand,Javascript,Shorthand,我希望将任何速记技巧融入到我的常规编码习惯中,并且当我在压缩代码中看到它们时,也能够阅读它们 有人知道概述技术的参考页或文档吗 编辑:我之前提到过缩微器,现在我很清楚,缩微和高效的JS键入技术是两个几乎完全不同的概念。更新了一些好东西。看下面 最常见的条件速记是: a = a || b // if a is falsy use b as default a || (a = b) // another version of assigning a default value a = b
编辑:我之前提到过缩微器,现在我很清楚,缩微和高效的JS键入技术是两个几乎完全不同的概念。更新了一些好东西。看下面 最常见的条件速记是:
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()
内置类型(数字、字符串、日期、布尔值)
变量声明:
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)支持,也可以通过Transpiler支持。当然,“旧”版本将继续有效 箭头功能
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
// 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
休息参数
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
// 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
默认参数值
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
// 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
解构
var bag = [1, 2, 3]
var [a, b, c] = bag // new
var a = bag[0], b = bag[1], c = bag[2] // old
对象文本内部的方法定义
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
// 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
对象文字中的计算属性名
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
// 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
奖励:内置对象上的新方法
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
// 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还包含比1.5版更新的版本,则还可以看到以下内容:
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');
表达式闭包: JavaScript 1.7及更高版本:
var square = function(x) { return x * x; }
JavaScript 1.8添加了一个用于编写简单函数的速记,其中包括:
reduce()方法: JavaScript 1.8还将该方法引入数组:
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中引入了以下代码:
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]);
}
}
或者使用JavaScript 1.6中引入的数组中的方法:
var numbers = [1, 2, 3, 21, 22, 30];
var evens = numbers.filter(function(i) { return i % 2 === 0; });
您正在寻找JavaScript语言的习惯用法
- 简明但不全面的列表:
- 道格拉斯·克罗克福德的建议:
yield
关键字)。但是,如果您没有接触过Lisp或Scheme,那么了解新的标准库函数是值得的。函数式编程的许多典型部分,例如,和,都是很好了解的,并且经常出现在JavaScript库中,比如jQuery;另一个有用的函数是(在jQuery中,在某种程度上),它在将方法指定为回调时非常有用。获取数组的最后一个值
这不是一个真正的速记,但更像是一个较短的替代技术,大多数人使用的技术
当我需要获取数组的最后一个值时,我通常使用以下技术:
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');
结论:使用这种速记法没有缺点
调试速记
大多数浏览器都支持每个id元素的隐藏全局变量。因此,如果我需要调试某些东西,我通常只需向元素添加一个简单的id,然后使用控制台通过全局变量访问它。您可以自己检查这个:只需在此处打开控制台,键入
footer
并按enter键。它很可能会返回这个github repo专用于Javascript字节保存技术的。我觉得很方便
我认为任何迷你们都不会做这些事情……:)@加拉姆巴拉兹:不,我也不这么认为。minifier这样做是不正确的,因为这样的转换会使代码在支持JavaScript版本1.5的引擎中不兼容。。。尽管如此,在以后的版本中,这些仍然是一些缩短代码的选项,可能更多的是为了可读性,而不是为了简化。@galambalazs:我没有这样解释这个问题:)。。。OP问:“我想在我的常规编码习惯中加入任何速记技巧……”JS1.7中的+1数组理解?我怎么不知道这件事<代码>语法错误:这是我为每个bla bla运行代码时得到的意外标记…x&&(doWhentrue)
所以在所有这些速记数学之后,pow(x,2)
仍然是求x平方的最短方法?x*x
是目前最短的方法:)尽管现代浏览器已经实现了求幂运算(ES7):所以你可以做x**2
,当然对其他指数更有用。注意!箭头函数的使用附带了一个警告,即此
在它们内部不可用。函数(){}与()=>{}不同,你让我开心!这个要点读起来很好,我刚刚学到了很多东西;)