2018.10.25 学习笔记前端JSES6新特性

xiaoxiao2025-08-05  25

 

1.const 与 let

//1 var a = 12; function fn(){ console.log(a); var a = 5; } fn(); //var有变量提升的问题,结果undefined var a = 12; function fn(){ console.log(a); let a = 5; } fn(); //let没有有变量提声,结果a is not defined function fn(){ var a = 5; } console.log(a); //a is not defined if(true){ var a = 5; } console.log(a); //5 还有for也是这种情况 //2 var a = 12; var a = 5; console.log(a); //5 let b = 12; let b = 5; console.log(b); //Identifier 'b' has already been declared //3 for(let i = 0; i < 3; i++){ let i = 'ab'; console.log(i); }; //ab ab ab var arr = []; for(let i = 0; i < 10; i++){ arr[i]=function(){ console.log(i) } } arr[5](); //const const a = 5; a = 6; console.log(a); //报错,下面的也无法执行 const arr = ['apple','banana']; arr.push('orange'); console.log(arr); //执行之后是[ 'apple', 'banana', 'orange' ] 本身对象的原因 const arr = Object.freeze(['apple','banana']); arr.push('orange'); console.log(arr); //报错 object is not extensible

{

//块级作用域

}

let:

没有预解析,不存在变量提声。在代码块内,只要let定义变量,在之前使用,都是报错。先定义,再使用。不能重复定义变量。for循环,for( )是一个作用域,{ }又是一个作用域

const:

const定义变量是不能修改的const定义完必须有量const定义对象可以被修改,对象的原因

2.解构赋值:

let [a,b,c] = [1,2,3]; console.log(a,b,c); //1,2,3 let json = { name:'Betty', age:22, job:'工程师' } console.log(json.name,json.age,json.job); //一般用法,Betty 22 工程师 let {name,age,job} = { name:'Betty', age:22, job:'工程师' } console.log(name,age,job); //解构赋值 let {name,age,job:a} = { name:'Betty', age:22, job:'工程师' } console.log(name,age,a); //一种用法,给job换别名 //由上我们可以推得 let [a,b,c='暂无数据'] = ['aa','bb']; console.log(a,b,c); //加上暂无数据,这样c就可以不报错了 //交换a,b let a = 12; let b = 5; [a,b] = [b,a]; console.log(a,b); //函数传参也可以结构 function show({a,b}){ console.log(a,b); } show({ a:1, b:2 })

注意:左右两边,结构格式要保持一致

应用:交换a、b的值

3.字符串模板与字符串查找

//传统如下 let name = 'strive'; let age = '18'; let str = '这个人' + name + '年龄是' + age console.log(str); //这个人strive年龄是18 //字符串模板 let name = 'strive'; let age = '18'; let str = `这个人${name},年龄是${age}岁`; //这里用的是反单引号 console.log(str); //这个人strive,年龄是18岁

字符串查找新增了includes():

//传统 let str = 'apple banana pear'; if(str.indexOf('apple')!== -1){ console.log('true'); }else{ console.log('false'); }; //true //新增 let str = 'apple banana pear'; console.log(str.includes('banana')); //true

字符串查找:

str.indexOf(要找的东西) 返回索引(位置),没找到返回-1;str.includes(要找的东西) 返回值 true/false str.startsWith() 开头str.endsWith() 结尾str.repeat(次数) 重复字符串str.padStart(整个字符串长度,填充的东西)str.padEnd(整个字符串长度,填充的东西)

4.函数默认参数、剪头函数、剩余参数

function show(a='欢迎',b='mmr'){ console.log(a,b); } show('hah',); //hah mmr function show(a=18){ let a = 101; //错误? console.log(a); } show(); //报错:'a' has already been declared function show(a){ console.log(a); } show(1,2,3,4,5) //1 function show(a){ console.log(a); } show(1,2,3,4,5) //[ 1, 2, 3, 4, 5 ] function show(){ console.log(arguments); } show(1,2,3,4,5) //{ '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }

1.函数默认参数

2.函数参数默认已经定义了,再使用let const会报错

3.扩展运算符

          

转载请注明原文地址: https://www.6miu.com/read-5034294.html

最新回复(0)