目录
一、声明变量
1.let
let 允许创建块级作用域,ES6 推荐在函数中使用 let 定义变量,而非 var:
a. let是块级作用域(在一对大{} 里面起作用)
{ let a = 15;
console.log(a);}
b. 不能重复声明
{ let c = 22;
let c = 25;}
c. let声明变量不会变量提升
{ console.log(a);
let a = 15;}
2.const
a. 通常用来声明常量的 建议大写
const PI = 3.1415926;
console.log(PI);
b. 声明必须赋值
const FREEZON
c. 声明后不能修改*(复杂数据可以修改 数组)
const ARR = 15;
ARR = 22; //报错
二、解构
1.结构数组
解构就是把数组或者对象拆分为单个的变量
a. 交换变量
var a = 15;
var b = 88;
[a, b] = [b, a];
console.log("a:",a); console.log("b:",b)
b. 不定参(剩余值)与跳过
var arr = [1, 3, 9, 24, 74, 98, 202];
[c, ,d, ...rest] = arr;
console.log("c:",c); console.log("d:",d); console.log("rest:",rest);
c. 默认值
var arr1 = [2, 9];
[e,f,g=50] = arr1;
console.log("e:",e) console.log("f:",f) console.log("g:",g)
2.解构对象
变量名必须和对象键名一致
let o = {p:42, q:true};
let {p,q} = o;
console.log(p,q);
三、字符串
1.字符串模板
let name = "胡歌";
let age = "28";
let m = `我的名字是${name},${age}`;
console.log(m);
2.字符串检测
includes 包含
startsWith 以...开头 语法:string.startsWith(searchvalue, start)
endWith 以...结尾 语法:string.includes(searchvalue, start)
例子:let str = "string";
console.log('includes',str.includes("c"));
console.log('start',str.startsWith('str'));
console.log('end',str.endsWith('ng'));
3.字符串重复与填充
重复输出 repeat
let str = "123";
console.log(str.repeat(3));//123123123
填充 padStart / padEnd
console.log('1'.padStart(4,'0'));//0001
console.log('1'.padEnd(2,'0'))//10
四、函数
1.箭头函数
定义:ES6 中,箭头函数就是函数的一种简写形式,使用括号包裹参数,跟随一个 =>,紧接着是函数体;
①var getPrice = function() { return 4.55; };
var getPrice = () => 4.55;
=> 前面是函数参数 =>后面是返回值也是执行语句
②多个参数 或者没有 都用括号包起来
var arr3 = ["mumu","zql","曾庆林"]; arr3.forEach( (item,index,self) => console.log(item,index,self) )
③执行语句有多个的时候 用{}包括起来
var arr4 = [70,33,52,89,14,80,87];
var arr5 = arr4.filter( item => {
if(item>=70){return true}
else{return false} } )
④箭头函数this 指的是函数上一层的this
var obj = {
age:16,
grow:function(){
setTimeout(()=>{
this.age++;
console.log("我的年纪是"+this.age) }) } }
obj.grow();
2.默认参数
function say (age=18){
alert("大家好我今年"+age+"岁了") }
say(); //大家好我今年18岁了
say(16);//大家好我今年16岁了
3.参数不定
function add(...arg){
var total = 0; // 总数
arg.forEach(item=>total+=item); }
dd(1,2); //3
add(2,3,4); //2+3+4
add(2,1,1,6); //2+1+1+6
五、对象
1.对象简写
let color="白色";
let name = "Kitty";
let cat = {color,name};
console.log(cat) //{color:"白色",name:"Kitty"}
函数简写与动态属性值
var obj = { name:"木木", ["nick"+"name"]:"小木木", say(){alert(this.name)} } //nickname:"小木木"
2.super方法
var parent = {
foo() {
console.log("Hello from the Parent"); } }
var child = {
foo() {
super.foo();
console.log("Hello from the Child"); } }
Object.setPrototypeOf(child, parent); child.foo();
//Object.setPrototypeOf(a,b),为现有对象设置原型,返回一个新对象
//接收两个参数:第一个是现有对象,第二是原型对象。
child.foo(); // Hello from the Parent // Hello from the Child