原文:19+ JavaScript Shorthand Coding Techniquesjavascript
使用三目运算符,能够更简洁地把if else写成一行java
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';
当你把一个变量的值赋给另外一个变量,若是你要求原变量不能是空或者未定义,你有一长一短两种写法数组
if (variable1 !== null || variable1 !== undefined || variable1 !== '') { let variable2 = variable1; }
const variable2 = variable1 || 'new';
let x; let y; let z = 3;
写成less
let x, y, z=3;
(译者注:其实如今standard风格不推荐声明简写)函数
if (likeJavaScript === true) //简化为 if (likeJavaScript)
注意:这两个例子不严格相等,
likeJavaScript
还多是其余“为真”的值,参考这里ui
let a; if ( a !== true ) { // do something... } //简化为 let a; if ( !a ) { // do something... }
for (let i = 0; i < allImgs.length; i++) //简化为 for (let index of allImgs) //译者拓展,用于循环key,不推荐在数组使用 for (let index in allImgs)
其实就是第二点...this
可能你早就知道了,这是一个不用在末尾写一堆0的方法。例如1e7表明1后面跟7个0,也就是十进制的1000000。lua
for (let i = 0; i < 1e7; i++) {} // All the below will evaluate to true 1e0 === 1; 1e1 === 10; 1e2 === 100; 1e3 === 1000; 1e4 === 10000; 1e5 === 100000;
ES6提供的方法让你更简单地建立对象字面量,若是属性名和值同样的话,你能够以下缩写code
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));
另外,注意箭头函数里的this和普通函数不一样orm
function calcCircumference(diameter) { return Math.PI * diameter } // 简化为 calcCircumference = diameter => Math.PI * diameter
注意:这个状况下返回的必须是一行语句,若是返回对象要加()
,多行语句仍是用{}
和return
吧
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
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;
JavaScriptconst 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.`
能够代替一些数组操做,而且比数组操做更灵活
// 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 }
function foo(bar) { if(bar === undefined) { throw new Error('Missing parameter!'); } return bar; } // 简化为 mandatory = () => { throw new Error('Missing parameter!'); } foo = (bar = mandatory()) => { return bar; }
你可能用for循环写过一个find函数,可是ES6已经引入了这个新特性!
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' }
(译者:find跟filter的区别是filter返回数组,find只返回找到的第一个)
你知道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
双重按位非的效果等于Math.floor()
Math.floor(4.9) === 4 //true // 至关于 ~~4.9 === 4 //true
注意注意,这条确实不利于其余人看懂,须要合做的项目勿用,用了记得加注释
3 ** 3 === 3 * 3 * 3 //a ** b就是a的b次方,也不用调用Math的方法了