ECMAScript 6 中的快捷語法匯總及代碼示例
阿新 • • 發佈:2017-06-30
nim 基本上 slice cci ren return evaluate set tput
對於每個 JavaScript 開發人員,快捷語法都是必備技能之一,下面就集中介紹這些快捷語法。
三元運算符
傳統寫法
const x = 20; let answer; if (x > 10) { answer = ‘is greater‘; } else { answer = ‘is lesser‘; }
快捷語法
const answer = x > 10 ? ‘is greater‘ : ‘is lesser‘;
空值判定
傳統寫法
if (variable1 !== null || variable1 !== undefined || variable1 !== ‘‘) {
let variable2 = variable1;
}
快捷語法
const variable2 = variable1 || ‘new‘;
變量聲明
傳統寫法
let x;
let y;
let z = 3;
快捷語法
let x, y, z=3;
如果 true
傳統寫法
if (likeJavaScript === true)
快捷語法
if (likeJavaScript)
for 循環
傳統寫法
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
十進制指數
例如,1E7基本上是指,隨後7個零。它代表了小數基(其中的JavaScript解釋為浮子式)等於10,000,000
傳統寫法
for (let i = 0; i < 10000; i++) {}
快捷語法
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;
對象屬性(Object Property)
傳統寫法
const obj = { x:x, y:y };
快捷語法
const obj = { x, y };
箭頭函數 Arrow Functions
傳統寫法
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));
隱式返回 Implicit Return
傳統寫法
function calcCircumference(diameter) {
return Math.PI * diameter
}
快捷語法
calcCircumference = diameter => ( Math.PI * diameter; )
默認參數值 Default Parameter Values
傳統寫法
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
字符串模板 Template Literals
傳統寫法
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}`;
賦值解構 Destructuring Assignment
傳統寫法
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;
多行字符串 Multi-line String
傳統寫法
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.`
操作符傳播 Spread Operator
傳統寫法
// 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];
強制參數 Mandatory Parameter
傳統寫法
function foo(bar) {
if(bar === undefined) {
throw new Error(‘Missing parameter!‘);
}
return bar;
}
快捷語法
mandatory = () => { throw new Error(‘Missing parameter!‘); } foo = (bar = mandatory()) => { return bar; }
Array.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]
傳統寫法
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
Double Bitwise NOT
傳統寫法
Math.floor(4.9) === 4 //true
快捷語法
~~4.9 === 4 //true
ECMAScript 6 中的快捷語法匯總及代碼示例