ECMAScript 6 中的快捷语法汇总及代码示例

对于每个 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 中的快捷语法汇总及代码示例的更多相关文章
- 关于Nvelocity的主要语法和一些代码示例
context.Response.ContentType = "text/html"; VelocityEngine vltEngine = new VelocityEngine( ...
- 简:Spring中Bean的生命周期及代码示例
(重要:spring bean的生命周期. spring的bean周期,装配.看过spring 源码吗?(把容器启动过程说了一遍,xml解析,bean装载,bean缓存等)) 完整的生命周期概述(牢记 ...
- 浅谈 PHP 中的多种加密技术及代码示例
信息加密技术的分类 单项散列加密技术(不可逆的加密) 属于摘要算法,不是一种加密算法,作用是把任意长的输入字符串变化成固定长的输出串的一种函数 MD5 string md5 ( string $str ...
- c/c++中define用法详解及代码示例
https://blog.csdn.net/u012611878/article/details/52534622 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog. ...
- python---Numpy模块中创建数组的常用方式代码示例
要机器学习,这方面内容不可少. import numpy as np import time # 对比标准python实现和numpy实现的性能差异 def sum_trad(): start = t ...
- C#中构建多线程应用程序[转] ----代码示例
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- go中的方法以及自定义类型代码示例
package main import "fmt" type user struct { name string age int sex string } type admin s ...
- Go语言语法汇总(转)
Go语言语法汇总 分类: 技术2013-09-16 14:21 3007人阅读 评论(0) 收藏 举报 go语言golang并发语法 目录(?)[+] 最近看了看GoLang,把Go语言的语法 ...
- ECMASCRIPT 6中字符串的新特性
本文将覆盖在ECMAScript 6 (ES6)中,字符串的新特性. Unicode 码位(code point)转义 Unicode字符码位的长度是21位[2].而JavaScript的字符串,是1 ...
随机推荐
- lightOJ 1017 Brush (III) DP
题目链接:http://www.lightoj.com/volume_showproblem.php?problem=1017 搞了一个下午才弄出来,,,,, 还是线性DP做的不够啊 看过数据量就知道 ...
- jQuery选择器的优点
jQuery选择器的优点 相信小伙伴们对选择器并不陌生,从css1到css3的选择器有很多,但是JQuery都能完美的支持,而且API操作起来也特别方便好用,在很大程度上精简了代码,节约了很多性能.那 ...
- (5)微信二次开发 之 XML格式数据解析
1.首先理解一下html html的全名是:HyperText Transfer markup language 超级文本标记语言,html本质上是一门标记(符合)语言,在html里,这些标记是事先定 ...
- C++ 常见的 Undefined symbols for architecture *
出现 Undefined symbols for architecture x86_64: 的原因 1.函数申明了,却未被定义. 2.申明的虚函数未被实现. NOTE: a missing vtabl ...
- 又是一个MVP+RxJava+Retrofit的干货集中营
欢迎访问我的个人博客 ,未经允许不得转发 前言 今天想要与大家一起分享的是近一个星期内开发的一个新app--干货集中营客户端,其实网上已经有许多类似的项目,代码家也在他的干货集中营中推荐了几款优秀的作 ...
- nodejs6下使用koa2
koa2里面使用ES7的语法,如async.await所以需要运行在node7.6之后:但在node7.6之前也可以利用babel是的koa2可以运行. 首先项目中安装babel,和babel的几个模 ...
- Linux服务器的远程IP限制
系统环境: Linux-centOS+ubuntu 操作: 编辑允许通过IP 路径:vim /etc/hosts.allow sshd:192.168.1.1 编辑禁止通过IP 路径:vim /etc ...
- 1.Java 加解密技术系列之 BASE64
Java 加解密技术系列之 BASE64 序号 背景 正文 总结 序 这段时间,工作中 用到了 Java 的加解密技术,本着学习的态度,打算从这篇文章开始,详细的研究一番 Java 在加解密技术上有什 ...
- 卫星导航低噪声放大器芯片(LNA)-AT2659
AT2659 是一款专门针对中国 BDS(北斗卫星导航系统),美国的 GPS,俄罗斯的 GLONASS 和欧盟的 GALILEO 导航系统应用而设计的高增益.低噪声系数射频放大器. AT2659 芯 ...
- Windows下以Local模式调试SparkStreaming的WordCount例子
1.下载Windows版的NetCat https://eternallybored.org/misc/netcat/ 2.启动NetCat nc -l -p 9999 3.将SAPRK_HOME\c ...