当你想用一行代码来写if...else语句的时候,使用三元操做符是很是好的选择,例如:javascript
const x = 20; let answer; if (x > 10) { answer = 'is greater'; } else { answer = 'is lesser'; }
能够简写为:java
const answer = x > 10 ? 'is greater' : 'is lesser';
也能够嵌套if语句:数组
const big = x > 10 ? " greater 10" : x
当给一个变量分配另外一个值的时候,你可能想肯定初值不是null,undefined或空值。这时,你能够写一个多重条件的if语句:框架
if (variable1 !== null || variable1 !== undefined || variable1 !== '') { let variable2 = variable1; }
或者可使用短路求值的方法:less
const variable2 = variable1 || 'new';
在定义函数的时候,你可能须要先声明多个变量,例如:函数
let x; let y; let z = 3;
这时,你可使用简写的方式节省不少时间和空间,即同时声明多个变量:学习
let x, y, z=3;
这可能微不足道,但值得一提。在你作if条件检查的时候,其赋值操做能够省略,例如:ui
if (likeJavaScript === true)
能够简写为:this
if (likeJavaScript)
只有当likeJavaScript是真值的时候,以上两个语句才能够替换。若是判断假值,例如:code
let a; if ( a !== true ) { // do something... }
能够简写为:
let a; if ( !a ) { // do something... }
当你想使用纯 javascript 而不依赖外库(例如jQuery)的时候,这是很是有用的。
for (let i = 0; i < allImgs.length; i++)
能够简写为:
for (let index in allImgs)
也可使用Array.forEach:
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
短路求值
若是想经过判断参数是否为null或者undefined来分配默认值的话,咱们不须要写六行代码,而是可使用一个短路逻辑运算符,只用一行代码来完成相同的操做。例如:
let dbHost; if (process.env.DB_HOST) { dbHost = process.env.DB_HOST; } else { dbHost = 'localhost'; }
能够简写为:
const dbHost = process.env.DB_HOST || 'localhost';
当数字的尾部为不少的零时(如10000000),我们可使用指数(1e7)来代替这个数字,例如:
for (let i = 0; i < 10000; i++) {}
能够简写为:
for (let i = 0; i < 1e7; i++) {} // 下面都是返回 true 1e0 === 1; 1e1 === 10; 1e2 === 100; 1e3 === 1000; 1e4 === 10000; 1e5 === 100000;
在 JavaScript 中定义对象很简单,并且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));
咱们常用return语句来返回函数最终结果,仅有一行声明语句的箭头函数能隐式返回其值(这时函数必须省略{}以便省略return关键字)。若是想要返回多行语句,则须要使用()包围函数体。例如:
function calcCircumference(diameter) { return Math.PI * diameter } var func = function func() { return { foo: 1 }; };
能够简写为:
calcCircumference = diameter => ( Math.PI * diameter; ) var func = () => ({ foo: 1 });
咱们常常可使用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}`;
若是你正在使用任何流行的 Web 框架,那么你颇有可能使用数组或以对象本文的形式将数据在组件和 API 之间进行通讯。一旦数据对象到达一个组件,你就须要解压它。例如:
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;
也能够分配变量名:
// 最后一个变量名为 contact
const { store, form, loading, errors, entity:contact } = this.props;
若是你曾发现本身须要在代码中编写多行字符串,那么这估计就是你编写它们的方法,即在输出的多行字符串间用+来拼接:
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.`
扩展运算符
在ES6中,包括扩展运算符,它可使你的操做更简单,例如:
// 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];
也可使用扩展运算符:
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 会将函数参数设置为undefined,而其余一些语言则会报出警告或错误。想要执行参数分配,则可让if语句抛出undefined的错误,或者使用“强制参数”的方法。例如:
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()的数组函数。
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' }
简写 Object[key]
你知道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
这个函数能够完美的完成它的任务。可是,考虑一个场景,你有不少表单,你须要进行验证,但有不一样的字段和规则。那么,构建一个能够在运行时配置的通用验证函数不是很好吗?
// 对象验证规则 const schema = { first: { required:true }, last: { required:true } } // 通用验证函数 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 如今咱们就有了一个能够在全部的form中重用的验证函数,而无需为每一个form编写其自定义的验证函数啦!
按位运算符绝对是你初学 JavaScript 时了解的但一直没有用武之地的运算符。由于若是不处理二进制,谁会没事操做0和1呢?可是,双重按位非运算符很是实用,例如你可使用它来替代floor()函数,并且与其余相同的操做相比,按位运算符的操做速度更快。
Math.floor(4.9) === 4 //true
能够简写为:
~~4.9 === 4 //true
以上就是这篇文章的所有内容了,但愿本文的内容对你们的学习或者工做能带来必定的帮助~