目录
let与const关键字
let
1.let是块级作用域(在一对大{} 里面起作用)
{
let a = 15;
console.log(a);//15
}
2.不能重复声明
{
let c = 22;
let c = 25;
}
//报错
3.let声明变量不会变量提升
{
console.log(a);//报错
let a = 15;
}
const
1.通常用来声明常量的 建议大写
const PI = 3.1415926;
console.log(PI);
2.声明必须赋值
const FREEZON//报错
3.声明后不能修改*(复杂数据可以修改 数组)
const ARR = 15;
ARR = 22; //报错
let与const总结:
- let 关键词声明的变量不具备变量提升(hoisting)特性
- let 和 const 声明只在最靠近的一个块中(花括号内)有效
- 当使用常量 const 声明时,请使用大写变量,如:CAPITAL_CASING
- const 在声明时必须被赋值
解构数组
解构就是把数组或者对象拆分为单个的变量
1.交换变量
var a = 15;
var b = 88;
[a, b] = [b, a];
console.log("a:",a);//88
console.log("b:",b);//15
2.不定参(剩余值)与跳过
var arr = [1, 3, 9, 24, 74, 98, 202];
[c, ,d, ...rest] = arr;
console.log("c:",c);//c: 1
console.log("d:",d);//d: 9
console.log("rest:",rest);//[24, 74, 98, 202]
3.默认值
var arr1 = [2, 9];
[e,f,g=50] = arr1;
console.log("e:",e)//e: 2
console.log("f:",f)//f:9
console.log("g:",g)//g:50
解析对象
变量名必须和对象键名一致
let o = {p:42, q:true};
let {p,q} = o;
console.log(p,q);//42 true
字符串
字符串模板
let name = "Mewow";
let age = "18";
console.log(`我的名字是${name},${age}`);//我的名字是Mewow,18
字符串检测
includes 包含 / startsWith 以..开头 / endWith 以结尾
let str = "string";
console.log('includes',str.includes("c"));//includes false
console.log('start',str.startsWith('str'));//start true
console.log('end',str.endsWith('ng'));//end true
字符串-重复 repeat
let str = "我爱你!";
console.log(str.repeat(3));//我爱你!我爱你!我爱你!
字符串-填充 padStart / padEnd
console.log('1'.padStart(4,'0'));//0001
console.log('1'.padEnd(2,'0'));//10
函数
箭头函数
ES6 中,箭头函数就是函数的一种简写形式,使用括号包裹参数,跟随一个 =>,紧接着是函数体=>
1.前面是函数参数 =>后面是返回值也是执行语句
var getPrice = function() {
return 4.55;
};
//箭头函数
var getPrice = () => 4.55;
2.多个参数 或者没有 都用括号包起来
var arr3 = ["小明","小红","小兰"];
arr3.forEach(
(item,index,self) => console.log(item,index,self)
);
//小明 0 ['小明', '小红', '小兰']
//小红 1 ['小明', '小红', '小兰']
//小兰 2 ['小明', '小红', '小兰']
3.执行语句有多个的时候 用{}包括起来
var arr4 = [70,33,52,89,14,80,87];
var arr5 = arr4.filter(
item => {
if(item>=70){return true}
else{return false}
}
)
console.log(arr5);//[70, 89, 80, 87]
4.箭头函数this 指的是函数上一层的this
var obj = {
age:16,
grow:function(){
setTimeout(()=>{
this.age++;
console.log("我的年纪是"+this.age)
})
}
}
obj.grow();//我的年纪是17
函数默认参
function say (age=18){
alert("大家好我今年"+age+"岁了")
}
say();//大家好我今年18岁了
say(16);//大家好我今年16岁了
函数不定参
function add(...arg){
var total = 0; // 总数
arg.forEach(item=>total+=item);
console.log(total);
}
add(1,2);//3
add(2,3,4);//9
add(2,1,1,6);//10
对象
对象简写
let color="白色";
let name = "Kitty";
let cat = {color,name};
console.log(cat);//{color: '白色', name: 'Kitty'}
函数简写与动态属性值
var obj = {
name:"Mewow",
["nick"+"name"]:"Mewow",
say(){alert(this.name)}
}
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();
//Hello from the Parent
//Hello from the Child
总结
- var,let,const
const 与let 局部作用域 ,不能重复声明,不能变量提升,const声明常量
- 解构与拓展
...rest
- 字符串
``字符串模板,includes repeat pad
- 函数
箭头函=> 默认值
- 对象
对象简写;动态属性;与super方法