let
和const
变量声明的拓展
let
和var
ES5使用var
声明变量并没有块级作用域,会造成for
循环的变量污染,变量名重复和变量提升的问题。
ES6新增let
声明变量,变量只在代码块中有效,不存在变量提升的问题。- 暂时性死区
TDZ
const
和let
声明变量前均为暂时性死区,在暂时性死区中,变量不能够被使用。
TDZ的本质:进入作用域后,变量已存在但声明后才可获取。 const
声明常量,且必须初始化。
本质维护内存栈中的保存的数据或地址不变,因此基本数据类型不会改变,引用数据类型可以增添修改属性。
字符串的拓展
- 字符串遍历器接口
for of
可直接遍历字符串,但最大优点在于可识大于0xFFFF码点的字符串。 - 字符串的拓展方法
- 确定字符串是否存在
includes()
,startsWith()
,endsWith()
let str = "hello world" str.includes("o") //true str.includes("")//true str.startsWith("hello")//true str.endsWith("world")//true
- 重复字符串
"x".repeat(3)//"xxx"
- 补全字符串
"1".padStart(10,"0")//0000000001 "12".padStart(10,"YYYY-MM-DD")//YYYY-MM-12
- 模板字符串
${expression}
来表示多行字符串,或变量和函数 表达式
函数的拓展
- 参数默认值
- ES5变通给函数参数添加默认值,但必可避免
false
的情况
function log(x,y){
y=y || 'world'
console.log(x,y)
}
log('hello')//"hello world"
log('hello','')//"hello world"
//ES6中
function log(x,y="world"){
console.log(x,y)
}
log("hello","")//"hello"
function log(x=1,y=2){
console.log(x,y)
}
log(undefined,null)//1,null
length
属性,返回没有指定默认值参数的个数。
本质上是预期传入函数的参数个数,因此rest
参数并不包括在内。
rest
参数
rest
参数,用于获取函数多余的参数。替代了arguments
注:rest
参数必须是最后一个参数- 严格模式
ES6规定,只要函数参数使用默认值,内部不可声明为use strict
- 箭头函数
- 箭头函数的
this
永远指向声明创建的对象,而不是ES5中指向执行的对象。
function Timer(){
this.s1 = 0
this.s2 = 0
setInterval(() => this.s1++,1000 )
setInterval(function(){
this.s2++
},1000)
}
var timer = new Timer()
setTimeout(() => console.log("s1",timer.s1),3100 )
setTimer(() => console.log("s2",timer.s2),3100)
//s1 3
//s2 0
- 箭头函数不能作为构造函数
原因:箭头函数中的并没有自己的this
,而是指向外部的this
。因此this
指向固化,并且不能作为构造函数new
Promise
- 提出
Promise
是异步编程的解决方案。
有以下两个特点
- 对象状态不受外界影响。只有三种状态:
pending
,fulfilled
和rejected
- 对象的状态改变只有两种可能:从
pending
到fulfilled
和从pending
到rejected
- 基本用法
resolve()
将Promise
的状态从peding
变为resolved
rejected
将Promise
状态从pending
变为rejected
let p = new Promise((resolve,reject) =>{
if(){
//异步操作成功
resolve()
}else{
//异步操作失败
reject()
}
})
p.then(fuction(data){
//状态为resolved时调用
},
function(err){
//状态为rejected时调用
})
-
Promise.prototype.then
方法
then
方法返回的是Promise
对象,因此可连续使用 -
Promise.prototype.catch
方法
catch
方法与then
的第二个参数作用一致。当状态变为rejected
或then
方法出错时执行。
- 错误会一直“冒泡”,直到被
catch
捕获为止
promise.all()
用于将多个Promise
对象包装成一个新Promise
实例
var p = Promise.all([p1,p2,p3])
- 当
p1,p2,p3
状态均为resolved
时,p
的状态才为resolved
- 当
p1,p2,p3
有一个被rejected
时,p
的状态就变味rejected
Promise.race()
用于将多个Promise
对象包装成一个新Promise
实例
var p = new Promise([p1,p2,p3])
- 只要
p1,p2,p3
中任意一个状态改变,p
就跟着改变
Promise.resolve('foo')
//等价于
new Promise(resolve => resolve('foo'))
Promise.reject()
Promise.reject('foo')
new Promise(reject => reject('foo'))
async
,await
,Generator
class
Set
和Map
ES6新增去重
new Set([NaN,NaN,1,1,{},{}])//{ NaN,1,{},{} }
set
去重的方式
{}.hasOwnProperty(val)
ES6新增hashMap键值对