1.变量的解析赋值
变量的解构赋值: (解析结构,给对应的变量赋值)
1.理解 :从对象或数组中提取数据,并赋值给对应的变量(多个);
2.对象的解构赋值:
let{n,age} = {n:"tom" ,age:12};
解析对象,则以对象{ }的形式来接收;
3.数组的解构赋值:
let[a,b]=[1,"ment"];
解析数组,则以数组[ ]的形式来接收;
4.用途
:给多个形参赋值;
<script type="text/javascript">
let obj={name:"kobe",age:18};
//1.对象的解构赋值
let {name,age,sex} = obj;
//定义全局变量,变量值从obj对象中提取;(根据属性名去取属性值)
//解析对象,则用{}的形式来接收;
//可以获取对象中的部分属性, 若获取对象中没有的属性,则值为undefined;
console.log(name,age,sex);
//2.数组的解构赋值
let arr=[1,3,5,"abc",true];
let [,,a,b]=arr;
//定义全局的变量,变量值从数组中提取;
//根据对应的数组下标位置去获取变量的值;
console.log(a,b); //5,abc
//应用
function foo({name,age}){ // {name,age} = obj
console.log(name,age);
}
foo(obj); //传参进去
</script>
2.模板字符串
1.作用:简化字符串的拼接;
2.使用:
*将拼接的字符串内容必须放在` `里面
*字符串中需要变化的部分,放在${ xxx }中。
<script type="text/javascript">
let obj={name:"kobe",age:18};
let str='我的名字叫:'+obj.name+",年龄为:"+obj.age
console.log(str);
//等同于
let str= `我的名字叫: ${obj2.name},我的年龄是: ${obj2.age}`
console.log(str);
//使用字符串模板
let obj3={name:"孙悟空",age:20 ,sex:"男"};
let str3=` 我的名字是:${obj3.name},我的年龄是${obj3.age},我的性别是:${obj3.sex} `;
console.log(str3);
</script>
3.简化对象写法
在对象中:
*省略同名的属性 ==》 当属性名和属性值同名时,属性名可以不写
*省略方法的function ==》 当属性的值为方法时,方法的function可以不写
<script type="text/javascript">
let username="kobe";
let age=39;
let obj={
username:username, //属性值使用全局的变量;
age:age,
getName:function(){
return this.username;
}
}
console.log(obj);
console.log(obj.getName());
let obj2={
username, //当属性名和属性值相同时,属性名可以不写;
age,
getName (){ //定义属性为方法时,属性:和方法的function可以不写;
return this.username;
}
}
console.log(obj2);
console.log(obj2.getName());
</script>
4.点点点运算符
用途:
1.rest(可变)参数
:用来取代arguments,比arguments灵活,只能是最后部分形参参数。
(函数中有一个隐含参数为arguments,arguments是一个伪数组,会将函数的实参都存储在里面;
arguments是伪数组,则不能调用数组中的一般方法.,如foreach遍历,
点点点运算符相当于存实参的真数组,可遍历 )
2.扩展运算符
let arr=[1,6];
let arr2=[2,3,4,5];
arr3=[1,...arr2,6]; 三点+arr2 ,则arr2遍历存储在arr3数组中的内容
console.log(arr3); 输入数组
console.log(...arr3); 遍历arr3的内容,并输出
function foo(a,b){
console.log(arguments);
console.log(arguments.length); //arguments中实参长度
console.log(arguments[0]); //第一个实参;
arguments.forEach(function(item,index){ //不能遍历,报错
console.log(item,index);
})
}
foo(20,30);
//arguments是伪数组,则不能调用数组的forEach()方法遍历;
//es6中则提供了3点运算符,相当于一个存实参的真数组,则可以遍历
//...+取代arguments的变量
function fun(...value){ //value相当于一个真数组,存实参,名字可以任意取
console.log(arguments);
console.log(value);
value.forEach(function(item,index){
console.log(item,index);
})
}
fun(50,100);
//若前面占位了,则3点运算符的参数不存储占位的参数,
function fun2(a,...value){
value.forEach(function(item,index){
console.log(item,index);
})
}
fun2(50,100,200);
5.形参默认值
当不传入参数的时候默认使用形参里的默认值
function Point(x=1,y=2){
this.x=x;
this.y=y
}
<script type="text/javascript">
function Point(x,y){
this.x=x;
this.y=y;
}
let p=new Point(5,7);
console.log(p);
let p2=new Point();
//当我们忘记传实参进去时,则形参默认是未赋值,为undefined;
console.log(p2);
function Point2(x=0,y=0){
this.x=x;
this.y=y;
}
let p3=new Point2(8,9); //传值进去则会覆盖形参里的默认值
console.log(p3);
let p4=new Point2();
//当我们忘记传实参进去时,则使用形参的默认值;
console.log(p4);
</script>