ES6学习
目录
let和const
let
ES6 可以使用 let 关键字来实现块级作用域。
let 声明的变量只在 let 命令所在的代码块 {} 内有效,在 {} 之外不能访问。
const
const 声明一个只读的常量,一旦声明,常量的值就不能改变。
当然这个变量声明时就必须赋值,如果他的值是一个对象,对象可以改变。
解构赋值
数组解构赋值
{
let a,b,rest
[a,b]=[1,2]
console.log(a,b) //输出1 2
}
{
let a,b,rest
[a,b,...rest]=[1,2,3,4,5,6]
console.log(a,b,rest) //输出1 2 3 4 5 6
}
对象解构赋值
{
let a,b
({a,b}={a:1,b:2})
console.log(a,b)
}
使用方法
默认值
{
let a,b,rest
//[a,b,c=3]=[1,2]
//console.log(a,b,c) //输出1 2 3
[a,b,c]=[1,2]
console.log(a,b,c) //输出1 2 undefined
}
变量交换
let a = 1
let b = 2
[a,b] = [b,a]
console.log(a,b) //输出 2 1
函数结构赋值
{
function f(){
return [1,2]
}
let a,b
[a,b]=f()
console.log(a,b) //输出1 2
}
{
function f(){
return [1,2,3,4,5]
}
let a,b
[a,,,b]=f()
console.log(a,b) //输出1 4
}
{
function f(){
return [1,2,3,4,5]
}
let a,b
[a,,...b]=f()
console.log(a,b) //输出1 [3,4,5]
}
json应用
{
let metaData = {
title: 'ESTitle',
test: [{
title: 'CNTitle',
desc: 'description'
}]
}
let {
title: esTitle, test[{
title: cnTitle}]} = metaData
console.log(esTitle,cnTitle) //输出 ESTitle CNTitle
}
字符串扩展
字符串遍历
{
let str='\u{20bb7}ab'
for(let i=0;i<str.length;i++){
console.log('es5',str[i]) //输出 乱码 乱码 a b
}
for(let code of str){
console.log('es6',code) //输出 乱码 乱码 a b
}
}
字符串操作
{
let str='string'
console.log(str.includes('c')) //false
console.log(str.startsWith('str')) //true
console.log(str.endsWith('ng')) //true
console.log(str.repeat(2)) //stringstring
}
模板字符串
{
let name='list'
let info='hello world'
let m=`i am $(name),$(info)`
console.log(m) //输出i am list,hello world
}
ES7草案API
导入babel-polyfill可以使用
补白
{
console.log('1',padStart(2,'0')) //输出 02
console.log('1',padEnd(2,'0')) //输出 20
}
标签模板
用处:
- 防止XSL攻击
- 处理多语言转换
{
let user = {
name:'list',
info:'hello world'
}
abc`i am ${
user.name},${
user.info}`
function abc(s,v1,v2){
console.log(s,v1,v2)
return s+v1+v2
}
}
数组扩展
Array.of()
把一组数据变量转换成数据类型的作用
如果其中不放参数则返回空数组
{
let arr=Array.of(1,2,3,4,5)
console.log(arr) //输出 [1,2,3,4,5]
let empty=Array.of()
console.log(empty) //[]
}
Array.from()
把一些伪数组转换成真正的数组
{
let p=document.querySeletorAll('p')
let pArr=Array.from(p) //把集合转换成了一个数组
pArr.forEach(function(item){
console.log(item.textContent)
})
console.log(Array.from([1,3,5],function(item){
return item*2})) //类似映射 输出 2 6 10
}
Array.fill()
填充数组
console.log([1,'a',undefined].fill(7)) //[7,7,7]
console.log(['a','b','c'].fill(7,1,3)) //从第一个开始换一直到第三个替换第一个和第二个 输出 ['a',2,3]
keys,values,entries
{
for(let index of [1,'c','ks'].keys()){
console.log('keys',index) // 0 1 2
}
for(let value of [1,'c','ks'].values()){
//存在兼容问题
console.log('values',value)
}
for(let [index,value] of [1,'c','ks'].entries()){
//不存在兼容问题
console.log