Skip to content

ECMASCRIPT 6 #16

@1StepEngineer

Description

@1StepEngineer

常量 const

块级作用域 let

var callbacks = []
for(var i = 0;i <= 2; i++){
    callbacks[i] = function(){
      return i*2  
 }
}
 console.table([callbacks[0](),callbacks[1](),callbacks[2]()])

执行结果:

(index) value
0 6
1 6
2 6

分析:var 有变量提升的作用,当在调用callbacks0时,闭包里的 i 值已经变成3,所以结果均为6。

const callbacks = []
for(let i= 0;i <= 2; i++){
    callbacks[i] = function(){
      return i*2  
 }
}
 console.table([callbacks[0](),callbacks[1](),callbacks[2]()]) 

执行结果:

(index) value
0 0
1 2
2 4

分析:let提供了块级作用域,在每次for循环的时候,{ }都保存了当前的块级作用域,当调用callback0时,闭包就会调用当前作用域的i值(这边就是保存下的 i=0)。

新数据格式

Set

类似数组,值无重复值,都是唯一值。去除重复值时在

 new Set([1,1,3,3]) // [1,3],仅仅当里面值未数值型数组时起作用

Map

箭头函数

(1)简化代码,使得代码显示更加简洁。
(2)箭头函数体内的this对象,就是定义时所在的对象,而不是调用时所在的对象。
this对象的指向是可变的,但是在箭头函数中,它是固定的

默认参数

(1)默认参数
es5:

function a(x,y){
 x = x || 1
 y = y || 2
}

es6:

function a(x=1,y=2){
}

(2)判断参数必填
判断参数必填

function checkParam(){
  throw new Error('can\'t be empty')
}
function sum(a = checkParam(),b = 2){
  return a + b
}
try{
  sum()
}catch(e){
  console.log(e)
}finally{}

输出:

Error: can't be empty
    at checkParam (<anonymous>:2:9)
    at sum (<anonymous>:4:18)
    at <anonymous>:8:3

(3)参数未知数
es5:

function f(){
 var a = Array.prototype.slice.call(arguments)
 var sum = 0
a.forEach((item,key) => {
  sum += item
   return sum
})
}
console.log(f(1,2,3))

es6:

function f(...a){
 var sum = 0
 a.forEach(item => {
  sum += item * 1
})
return sum
}
console.log(f(1,2,3,6))

...在es6中就是扩展运算符

扩展运算符用途——合并数组

es5:

var params = ['hello',true,7]
var other = [1,2].concat(params)  //通过concat方法进行拼接
console.log(other)  // [1, 2, "hello", true, 7] 

es6:

let params = ['hello',true,7]
let other = [1,2, ...params]
console.log(other)   // [1, 2, "hello", true, 7]

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions