Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:
模板字面量,也叫模板字符串
模板字面量,可以理解为字符串的升级版,它完全可以代替传统的字符串声明,并且还可以在内部直接解析变量
let site='www.baidu.com';
site=`${site}(php中文网)`;
console.log(site);
let num=20;
let price=100;
function fun(string,var1,var2){
let res=`${string[0]}: ${var1}, ${string[1]}:${var2},${string[2]}:${var1 * var2}`;
return res;
}
let sum=fun`商品数量 ${num}, 单价 ${price}, 总计 ${num * price}`;
console.log(sum);
string 代表 所有字符集合['商品数量','单价','总计'];
任何类型都可以解构,用的最多的往往是对象和数组
注意:解构要求等号两边类型一致
1.对象解构
<script>
({name,age}={name:'jacke',age:53});
console.log(name,age);
/*默认值*/
({name,age,email='qq@.com'}={name:'jacke',age:53});
console.log(name,age,sex);
/*别名*/
({name:ming,age:old}={name:'jacke',age:53});
console.log(ming,old);
</script>
<script>
const colors=['red','green','blue'];
let [color1,color2,color3]=colors;
console.log(color1,color2,color3);
</script>
<script>
let score=2;
if(score>6)console.log('合格');
else if(score>6 && score<8)console.log('优良');
else console.log('不合格');
</script>
2.switch
<script>
let res='success';
switch(res){
case 'fail':console.log('失败!');break;
case 'success':console.log('成功!');break;
default:console.log('平手');
}
</script>
注意:switch 通常不去做区间判断,而是用于单值判断
3.三元运算
let str=(score>=60)?'及格了':'补考吧!';
<script>
const arr=[1,2,3,4,5];
let i=0;
while(i<arr.length){
console.log(arr[i]);
i++;
}
或
i=0;
do{
console.log(arr[i]);
i++;
}while(i<arr.length);
</script>
<script>
let arr=[1,2,3,4,5];
for(let i=0;i<arr.length;i++){
//当i大于等于2时,则退出,不再往下执行
if(i>=2)break;
console.log(arr[i]);
}
//对象遍历
const user={
id:5,
name:'jacke',
age:53
};
for(let key in user){
//key是键
console.log(`${key} --- ${user[key]}`);
}
</script>