1. const和let关键字

const用于定义常量。 let用于定义变量。但是JavaScript中不是已经有变量了吗? 是的,这很正确,但用var声明的变量具有函数作用域,并会被提升到顶部。 这意味着在声明之前就可以使用这个变量。 let变量和常量具有块作用域(用{}包围),在声明之前不能被使用。

  1. function f() {
  2. var x = 1
  3. let y = 2
  4. const z = 3
  5. {
  6. var x = 100
  7. let y = 200
  8. const z = 300
  9. console.log('x in block scope is', x)
  10. console.log('y in block scope is', y)
  11. console.log('z in block scope is', z)
  12. }
  13. console.log('x outside of block scope is', x)
  14. console.log('y outside of block scope is', y)
  15. console.log('z outside of block scope is', z)
  16. }
  17. f()
  1. x in block scope is 100
  2. y in block scope is 200
  3. z in block scope is 300
  4. x outside of block scope is 100
  5. y outside of block scope is 2
  6. z outside of block scope is 3

2. 数组助手函数

非常酷的助手函数出现了。像这样的逻辑你实现了多少次了:过滤,检查是否有元素满足条件,然后进行元素转换。也许有无数次吧。现在,有一些非常强大的功能可以代替你做这些事情。在我看来,这些是最有价值的功能:

forEach

对数组的每个元素执行所提供的函数,将数组元素作为参数传递进入。

  1. var colors = ['red', 'green', 'blue']
  2. function print(val) {
  3. console.log(val)
  4. }
  5. colors.forEach(print)
  1. red
  2. green
  3. blue

map

创建一个包含相同数量元素的新数组,但是由提供的函数创建输出元素。它只是将数组中的每个元素做了转换。

  1. var colors = ['red', 'green', 'blue']
  2. function capitalize(val) {
  3. return val.toUpperCase()
  4. }
  5. var capitalizedColors = colors.map(capitalize)
  6. console.log(capitalizedColors)
  1. ["RED","GREEN","BLUE"]

filter

创建一个包含原始数组子集的新数组。新数组的元素则是那些通过了所提供函数测试的元素,测试函数应返回true或false。

  1. var values = [1, 60, 34, 30, 20, 5]
  2. function lessThan20(val) {
  3. return val < 20
  4. }
  5. var valuesLessThan20 = values.filter(lessThan20)
  6. console.log(valuesLessThan20)
  1. [1,5]

find

找到通过所提供函数测试的第一个元素,测试函数应返回true或false。

  1. var people = [
  2. {name: 'Jack', age: 50},
  3. {name: 'Michael', age: 9},
  4. {name: 'John', age: 40},
  5. {name: 'Ann', age: 19},
  6. {name: 'Elisabeth', age: 16}
  7. ]
  8. function teenager(person) {
  9. return person.age > 10 && person.age < 20
  10. }
  11. var firstTeenager = people.find(teenager)
  12. console.log('First found teenager:', firstTeenager.name)
  1. First found teenager: Ann

every

检查数组的每个元素是否通过所提供函数的测试,测试函数应返回true或false。

  1. var people = [
  2. {name: 'Jack', age: 50},
  3. {name: 'Michael', age: 9},
  4. {name: 'John', age: 40},
  5. {name: 'Ann', age: 19},
  6. {name: 'Elisabeth', age: 16}
  7. ]
  8. function teenager(person) {
  9. return person.age > 10 && person.age < 20
  10. }
  11. var everyoneIsTeenager = people.every(teenager)
  12. console.log('Everyone is teenager: ', everyoneIsTeenager)
  1. Everyone is teenager: false

some

检查数组中是否有某个元素能够通过所提供函数的测试,测试函数应返回true或false。

  1. var people = [
  2. {name: 'Jack', age: 50},
  3. {name: 'Michael', age: 9},
  4. {name: 'John', age: 40},
  5. {name: 'Ann', age: 19},
  6. {name: 'Elisabeth', age: 16}
  7. ]
  8. function teenager(person) {
  9. return person.age > 10 && person.age < 20
  10. }
  11. var thereAreTeenagers = people.some(teenager)
  12. console.log('There are teenagers:', thereAreTeenagers)
  1. There are teenagers: true

reduce

第一个参数是一个函数,该函数的参数为一个累加器以及数组中的每个元素(从左到右),并最终输出单个值。累加器的初始值则由reduce函数的第二个参数提供。

  1. var array = [1, 2, 3, 4]
  2. function sum(acc, value) {
  3. return acc + value
  4. }
  5. function product(acc, value) {
  6. return acc * value
  7. }
  8. var sumOfArrayElements = array.reduce(sum, 0)
  9. var productOfArrayElements = array.reduce(product, 1)
  10. console.log('Sum of', array, 'is', sumOfArrayElements)
  11. console.log('Product of', array, 'is', productOfArrayElements)
  1. Sum of [1,2,3,4] is 10
  2. Product of [1,2,3,4] is 24

3. 箭号函数

有时候,实现一些简单的功能也需要编写大量的重复代码。有什么补救办法吗?有,请尝试一下箭头函数!

  1. var array = [1, 2, 3, 4]
  2. const sum = (acc, value) => acc + value
  3. const product = (acc, value) => acc * value
  4. var sumOfArrayElements = array.reduce(sum, 0)
  5. var productOfArrayElements = array.reduce(product, 1)

箭头函数也可以内联。它真的让代码更简单了:

  1. var array = [1, 2, 3, 4]
  2. var sumOfArrayElements = array.reduce((acc, value) => acc + value, 0)
  3. var productOfArrayElements = array.reduce((acc, value) => acc * value, 1)

箭头函数也可以更复杂:

  1. var array = [1, 2, 3, 4]
  2. const sum = (acc, value) => {
  3. const result = acc + value
  4. console.log(acc, ' plus ', value, ' is ', result)
  5. return result
  6. }
  7. var sumOfArrayElements = array.reduce(sum, 0)

4. 类

当转移到JS项目的时候,哪个Java开发人员不会错过类?谁不喜欢像Java语言那样的显式继承?虽然一些JS开发者对此非常抱怨,但ES6实际已经引入了类的概念。它们不改变继承这个概念,它们只是原型继承的语法糖。

  1. class Point {
  2. constructor(x, y) {
  3. this.x = x
  4. this.y = y
  5. }
  6. toString() {
  7. return '[X=' + this.x + ', Y=' + this.y + ']'
  8. }
  9. }
  10. class ColorPoint extends Point {
  11. static default() {
  12. return new ColorPoint(0, 0, 'black')
  13. }
  14. constructor(x, y, color) {
  15. super(x, y)
  16. this.color = color
  17. }
  18. toString() {
  19. return '[X=' + this.x + ', Y=' + this.y + ', color=' + this.color + ']'
  20. }
  21. }
  22. console.log('The first point is ' + new Point(2, 10))
  23. console.log('The second point is ' + new ColorPoint(2, 10, 'green'))
  24. console.log('The default color point is ' + ColorPoint.default())
  1. The first point is [X=2, Y=10]
  2. The second point is [X=2, Y=10, color=green]
  3. The default color point is [X=0, Y=0, color=black]

5. 增强的对象字面量

对象字面量已得到了增强。现在我们可以更容易地: 
- 定义具有相同名称的变量赋值字段 
- 定义函数 
- 定义动态属性

  1. const color = 'red'
  2. const point = {
  3. x: 5,
  4. y: 10,
  5. color,
  6. toString() {
  7. return 'X=' + this.x + ', Y=' + this.y + ', color=' + this.color
  8. },
  9. [ 'prop_' + 42 ]: 42
  10. }
  11. console.log('The point is ' + point)
  12. console.log('The dynamic property is ' + point.prop_42)
  1. The point is X=5, Y=10, color=red
  2. The dynamic property is 42

6. 模板字符串

谁喜欢写一连串的字符串与变量的连接?我相信只有极少数人会喜欢。谁讨厌阅读这样的连接?每个人。幸运的是,ES6引入了非常易于使用的带有占位符的字符串模板。

  1. function hello(firstName, lastName) {
  2. return `Good morning ${firstName} ${lastName}!
  3. How are you?`
  4. }
  5. console.log(hello('Jan', 'Kowalski'))
  1. Good morning Jan Kowalski!
  2. How are you?

请注意,我们可以将文本写成多行。

重要提示:请使用反引号而不是撇号来将文本包围起来。

7. 默认函数参数

你不喜欢提供所有可能的函数参数?请使用默认值。

  1. function sort(arr = [], direction = 'ascending') {
  2. console.log('I\'m going to sort the array', arr, direction)
  3. }
  4. sort([1, 2, 3])
  5. sort([1, 2, 3], 'descending')
  1. I'm going to sort the array [1,2,3] ascending
  2. I'm going to sort the array [1,2,3] descending

8. Rest和Spread操作符

Spread

它可以将数组或对象内容提取为单个元素。 
示例 - 数组的浅拷贝:

  1. var array = ['red', 'blue', 'green']
  2. var copyOfArray = [...array]
  3. console.log('Copy of', array, 'is', copyOfArray)
  4. console.log('Are', array, 'and', copyOfArray, 'same?', array === copyOfArray)
  1. Copy of ["red","blue","green"] is ["red","blue","green"]
  2. Are ["red","blue","green"] and ["red","blue","green"] same? false

示例 - 合并数组:

  1. var defaultColors = ['red', 'blue', 'green']
  2. var userDefinedColors = ['yellow', 'orange']
  3. var mergedColors = [...defaultColors, ...userDefinedColors]
  4. console.log('Merged colors', mergedColors)
  1. Merged colors ["red","blue","green","yellow","orange"]

Rest

要将前几个函数参数绑定到指定变量,而将其他参数作为数组绑定到单个变量上吗?现在你可以很容易地做到这一点。

  1. function printColors(first, second, third, ...others) {
  2. console.log('Top three colors are ' + first + ', ' + second + ' and ' + third + '. Others are: ' + others)
  3. }
  4. printColors('yellow', 'blue', 'orange', 'white', 'black')
  1. Top three colors are yellow, blue and orange. Others are: white,black

9. 解构

对于数组

从数组中提取指定元素并将其赋值给变量。

  1. function printFirstAndSecondElement([first, second]) {
  2. console.log('First element is ' + first + ', second is ' + second)
  3. }
  4. function printSecondAndFourthElement([, second, , fourth]) {
  5. console.log('Second element is ' + second + ', fourth is ' + fourth)
  6. }
  7. var array = [1, 2, 3, 4, 5]
  8. printFirstAndSecondElement(array)
  9. printSecondAndFourthElement(array)
  1. First element is 1, second is 2
  2. Second element is 2, fourth is 4

对于对象

从对象中提取指定的属性,并将其赋值给具有相同名称的变量。

  1. function printBasicInfo({firstName, secondName, profession}) {
  2. console.log(firstName + ' ' + secondName + ' - ' + profession)
  3. }
  4. var person = {
  5. firstName: 'John',
  6. secondName: 'Smith',
  7. age: 33,
  8. children: 3,
  9. profession: 'teacher'
  10. }
  11. printBasicInfo(person)
  1. John Smith - teacher

10. Promises

Promise承诺,你将会得到延时任务或者长期运行任务的未来结果。Promise有两个通道:第一个为结果,第二个为潜在的错误。要获取结果,你要将回调函数作为“then”的函数参数。要处理错误,你要将回调函数作为“catch”的函数参数。

请注意,由于函数调用是随机的,所以,示例每次执行的输出可能是不同的。

  1. function asyncFunc() {
  2. return new Promise((resolve, reject) => {
  3. setTimeout(() => {
  4. const result = Math.random();
  5. result > 0.5 ? resolve(result) : reject('Oppps....I cannot calculate')
  6. }, 1)
  7. });
  8. }
  9. for (let i=0; i<10; i++) {
  10. asyncFunc()
  11. .then(result => console.log('Result is: ' + result))
  12. .catch(result => console.log('Error: ' + result))
  13. }
  1. Result is: 0.7930997430022211
  2. Error: Oppps....I cannot calculate
  3. Result is: 0.6412258210597288
  4. Result is: 0.7890325910244533
  5. Error: Oppps....I cannot calculate
  6. Error: Oppps....I cannot calculate
  7. Result is: 0.8619834683310168
  8. Error: Oppps....I cannot calculate
  9. Error: Oppps....I cannot calculate
  10. Result is: 0.8258410427354488

ES6十大特性(转载CSDN)的更多相关文章

  1. 前端开发者不得不知的ES6十大特性

    前端开发者不得不知的ES6十大特性 转载 作者:AlloyTeam 链接:http://www.alloyteam.com/2016/03/es6-front-end-developers-will- ...

  2. 前端开发者不得不知的es6十大特性(转)

    转载自AlloyTeam:http://www.alloyteam.com/2016/03/es6-front-end-developers-will-have-to-know-the-top-ten ...

  3. 不得不知的ES6十大特性

    ES6(ECMAScript2015)的出现,无疑给前端开发人员带来了新的惊喜,它包含了一些很棒的新特性,可以更加方便的实现很多复杂的操作,提高开发人员的效率. 本文主要针对ES6做一个简要介绍. 主 ...

  4. ES6十大特性

    本文主要针对ES6做一个简要介绍. 主要译自:  http://webapplog.com/ES6/comment-page-1/.也许你还不知道ES6是什么, 实际上, 它是一种新的javascri ...

  5. ES6的十大特性和认知

    ---恢复内容开始--- ES6(ECMAScript2015)的出现,无疑给前端开发人员带来了新的惊喜,它包含了一些很棒的新特性,可以更加方便的实现很多复杂的操作,提高开发人员的效率.本文主要针对E ...

  6. jdk8十大特性并代码demo(转)

    一.十大特性 1.Lambda表达式 2.Stream函数式操作流元素集合 3.接口新增:默认方法与静态方法 4.方法引用,与Lambda表达式联合使用 5.引入重复注解 6.类型注解 7.最新的Da ...

  7. 总结JAVA语言的十大特性

    JAVA语言的十大特性 1.简单 Java语言的语法简单明了,容易掌握从,而且Java语言是纯面向对象的语言. Java语言的语法规则和C++类似,从某种意义上来讲,Java原因是由C语言和C++语言 ...

  8. ECMAScript 6十大特性

    ES6入门 http://es6.ruanyifeng.com/ ES6排名前十的最佳特性列表 Default Parameters(默认参数) in ES6 Template Literals (模 ...

  9. ES6十大常用特性

    .   Default Parameters(默认参数) in ES6 2.    Arrow Functions (箭头函数)in ES6 3.    Block-Scoped Constructs ...

随机推荐

  1. Java中常用的解决乱码的几种方法

    乱码有时候是一个非常让人头疼的问题,这里就总结一下常用的解决乱码的方法. 只知道的用法,却不明白为什么这么用…… 一. 在Java代码中: request.setCharacterEncoding(& ...

  2. 关于audio不能拖放

    图一,图二均为wav格式文件 图一为播放本地的音频,可以拖放 图二为放在后台的音频,不可以拖放 把这两个图片发给后台,让后台分析下两个的headers不同之处

  3. Django框架(十七)—— 中间件、CSRF跨站请求伪造

    目录 中间件 一.什么是中间件 二.中间件的作用 三.中间件执行顺序 四.自定义中间件 1.导包 2.定义类,继承MiddlewareMixin 3.在视图函数中定义一个函数 4.在settings的 ...

  4. Python 常见报错类型

    一.TypeError:类型错误,对象用来表示值的类型非预期类型时发生的错误 错误例子: age=18 print(‘我的年龄是’+age) 报错信息:TypeError: can only conc ...

  5. 進階gdb之core dump的除錯

    core dump的除錯 Basic Perl等語言處理的可以說是User的資料, C可以說在那邊把資料在記憶體移來移去, 組語可說把資料在暫存器搬來搬去, 越低階的處理表示握有的資源越少 所以C處理 ...

  6. 一个完整实用的axios封装

    1.先引入 import axios from 'axios' import qs from 'qs'import router from '../router'; import store from ...

  7. vue+Mint-ui实现登录注册

    创建一个组件:注册组件 (register/index.vue.script.js.style.scss,register/header) 注册路由 router/index.js { path: ' ...

  8. Redis事务 和 pipleline

    1.reidis事务 Redis 事务可以一次执行多个命令, 并且带有以下三个重要的保证: 批量操作在发送 EXEC 命令前被放入队列缓存. 收到 EXEC 命令后进入事务执行,事务中任意命令执行失败 ...

  9. MHA-Atlas-MySQL高可用(下)

    MHA-Atlas-MySQL高可用(下) 链接:https://pan.baidu.com/s/17Av92KQnJ81Gc0EmxSO7gA 提取码:a8mq 复制这段内容后打开百度网盘手机App ...

  10. 聚合函数 -AVG/MAX/MIN/STDDEV/VARIANCE/SUM/COUNT/MEDIAN

    ------------------------------------------聚合函数--------------------------------------------- --1: AVG ...