本文来源于多年的 JavaScript 编码技术经验,适合全部正在使用 JavaScript 编程的开发人员阅读。javascript
本文的目的在于帮助你们更加熟练的运用 JavaScript 语言来进行开发工做。java
文章将分红初级篇和高级篇两部分,分别进行介绍。nginx
下面是一个很好的例子,将一个完整的 if 语句,简写为一行代码。es6
const x = 20; let answer; if (x > 10) { answer = 'greater than 10'; } else { answer = 'less than 10'; }
简写为:编程
const answer = x > 10 ? 'greater than 10' : 'less than 10';
当使用纯 JavaScript(不依赖外部库,如 jQuery 或 lodash)时,下面的简写会很是有用。数组
for (let i = 0; i < allImgs.length; i++)
简写为:bash
for (let index of allImgs)
下面是遍历数组 forEach 的简写示例:less
function logArrayElements(element, index, array) { console.log("a[" + index + "] = " + element); } [2, 5, 9].forEach(logArrayElements); // logs: // a[0] = 2 // a[1] = 5 // a[2] = 9
在函数开始以前,对变量进行赋值是一种很好的习惯。在申明多个变量时:函数
let x; let y; let z = 3;
能够简写为:测试
let x, y, z=3;
在使用 if 进行基本判断时,能够省略赋值运算符。
if (likeJavaScript === true)
简写为:
if (likeJavaScript)
可使用科学计数法来代替较大的数据,如能够将 10000000 简写为 1e7。
for (let i = 0; i < 10000; i++) { }
简写为:
for (let i = 0; i < 1e7; i++) { }
若是须要在代码中编写多行字符串,就像下面这样:
const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t' + 'adipisicing elit, sed do eiusmod tempor incididunt\n\t' + 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t' + 'veniam, quis nostrud exercitation ullamco laboris\n\t' + 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t' + 'irure dolor in reprehenderit in voluptate velit esse.\n\t'
可是还有一个更简单的方法,只使用引号:
const lorem = `Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse.`
当将一个变量的值赋给另外一个变量时,首先须要确保原值不是 null、未定义的或空值。
能够经过编写一个包含多个条件的判断语句来实现:
if (variable1 !== null || variable1 !== undefined || variable1 !== '') { let variable2 = variable1; }
或者简写为如下的形式:
const variable2 = variable1 || 'new';
能够将下面的代码粘贴到 es6console 中,本身测试:
let variable1; let variable2 = variable1 || ''; console.log(variable2 === ''); // prints true variable1 = 'foo'; variable2 = variable1 || ''; console.log(variable2); // prints foo
若是预期参数是 null 或未定义,则不须要写六行代码来分配默认值。咱们能够只使用一个简短的逻辑运算符,只用一行代码就能完成相同的操做。
let dbHost; if (process.env.DB_HOST) { dbHost = process.env.DB_HOST; } else { dbHost = 'localhost'; }
简写为:
const dbHost = process.env.DB_HOST || 'localhost';
ES6 提供了一个很简单的办法,来分配属性的对象。若是属性名与 key 名相同,则可使用简写。
const obj = { x:x, y:y };
简写为:
const obj = { x, y };
经典函数很容易读写,可是若是把它们嵌套在其它函数中进行调用时,整个函数就会变得有些冗长和混乱。这时候可使用箭头函数来简写:
function sayHello(name) { console.log('Hello', name); } setTimeout(function() { console.log('Loaded') }, 2000); list.forEach(function(item) { console.log(item); });
简写为:
sayHello = name => console.log('Hello', name); setTimeout(() => console.log('Loaded'), 2000); list.forEach(item => console.log(item));
返回值是咱们一般用来返回函数最终结果的关键字。只有一个语句的箭头函数,能够隐式返回结果(函数必须省略括号({ }),以便省略返回关键字)。
要返回多行语句(例如对象文本),须要使用()而不是{ }来包裹函数体。这样能够确保代码以单个语句的形式进行求值。
function calcCircumference(diameter) { return Math.PI * diameter }
简写为:
calcCircumference = diameter => ( Math.PI * diameter; )
可使用 if 语句来定义函数参数的默认值。ES6 中规定了能够在函数声明中定义默认值。
function volume(l, w, h) { if (w === undefined) w = 3; if (h === undefined) h = 4; return l * w * h; }
简写为:
volume = (l, w = 3, h = 4 ) => (l * w * h); volume(2) //output: 24
过去咱们习惯了使用“+”将多个变量转换为字符串,可是有没有更简单的方法呢?
ES6 提供了相应的方法,咱们可使用反引号和 $ { } 将变量合成一个字符串。
const welcome = 'You have logged in as ' + first + ' ' + last + '.' const db = 'http://' + host + ':' + port + '/' + database;
简写为:
const welcome = `You have logged in as ${first} ${last}`; const db = `http://${host}:${port}/${database}`;
解构赋值是一种表达式,用于从数组或对象中快速提取属性值,并赋给定义的变量。
在代码简写方面,解构赋值能达到很好的效果。
const observable = require('mobx/observable'); const action = require('mobx/action'); const runInAction = require('mobx/runInAction'); const store = this.props.store; const form = this.props.form; const loading = this.props.loading; const errors = this.props.errors; const entity = this.props.entity;
简写为:
import { observable, action, runInAction } from 'mobx'; const { store, form, loading, errors, entity } = this.props;
甚至能够指定本身的变量名:
const { store, form, loading, errors, entity:contact } = this.props;
展开运算符是在 ES6 中引入的,使用展开运算符可以让 JavaScript 代码更加有效和有趣。
使用展开运算符能够替换某些数组函数。
// joining arrays const odd = [1, 3, 5]; const nums = [2 ,4 , 6].concat(odd); // cloning arrays const arr = [1, 2, 3, 4]; const arr2 = arr.slice( )
简写为:
// joining arrays const odd = [1, 3, 5 ]; const nums = [2 ,4 , 6, ...odd]; console.log(nums); // [ 2, 4, 6, 1, 3, 5 ] // cloning arrays const arr = [1, 2, 3, 4]; const arr2 = [...arr];
和 concat( ) 功能不一样的是,用户可使用扩展运算符在任何一个数组中插入另外一个数组。
const odd = [1, 3, 5 ]; const nums = [2, ...odd, 4 , 6];
也能够将展开运算符和 ES6 解构符号结合使用:
const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 }; console.log(a) // 1 console.log(b) // 2 console.log(z) // { c: 3, d: 4 }
默认状况下,若是不向函数参数传值,那么 JavaScript 会将函数参数设置为未定义。其它一些语言则会发出警告或错误。要执行参数分配,可使用if语句抛出未定义的错误,或者能够利用“强制参数”。
function foo(bar) { if(bar === undefined) { throw new Error('Missing parameter!'); } return bar; }
简写为:
mandatory = ( ) => { throw new Error('Missing parameter!'); } foo = (bar = mandatory( )) => { return bar; }
若是你曾经编写过普通 JavaScript 中的 find 函数,那么你可能使用了 for 循环。在 ES6 中,介绍了一种名为 find()的新数组函数,能够实现 for 循环的简写。
const pets = [
{ type: 'Dog', name: 'Max'}, { type: 'Cat', name: 'Karl'}, { type: 'Dog', name: 'Tommy'}, ] function findDog(name) { for(let i = 0; i<pets.length; ++i) { if(pets[i].type === 'Dog' && pets[i].name === name) { return pets[i]; } } }
简写为:
pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy'); console.log(pet); // { type: 'Dog', name: 'Tommy' }
虽然将 foo.bar 写成 foo ['bar'] 是一种常见的作法,可是这种作法构成了编写可重用代码的基础。
请考虑下面这个验证函数的简化示例:
function validate(values) { if(!values.first) return false; if(!values.last) return false; return true; } console.log(validate({first:'Bruce',last:'Wayne'})); // true
上面的函数完美的完成验证工做。可是当有不少表单,则须要应用验证,此时会有不一样的字段和规则。若是能够构建一个在运行时配置的通用验证函数,会是一个好选择。
// object validation rules const schema = { first: { required:true }, last: { required:true } } // universal validation function const validate = (schema, values) => { for(field in schema) { if(schema[field].required) { if(!values[field]) { return false; } } } return true; } console.log(validate(schema, {first:'Bruce'})); // false console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true
如今有了这个验证函数,咱们就能够在全部窗体中重用,而无需为每一个窗体编写自定义验证函数。
位操做符是 JavaScript 初级教程的基本知识点,可是咱们却不常使用位操做符。由于在不处理二进制的状况下,没有人愿意使用 1 和 0。
可是双位操做符却有一个很实用的案例。你可使用双位操做符来替代 Math.floor( )。双否认位操做符的优点在于它执行相同的操做运行速度更快。
Math.floor(4.9) === 4 //true
简写为:
~~4.9 === 4 //true
上述是一些经常使用的 JavaScript 简写技巧,若是有其它未说起的简写技巧,也欢迎你们补充。
原文连接:https://www.sitepoint.com/shorthand-javascript-techniques/
转载请注明出自:葡萄城控件