模板字面量
- 模板字面量, 也叫模板字符串
let name = 'jack';
- 模板字面量可以进行插值
let num = 30;
let price = 100;
let res = '商品数量:' + num + ' , 单价: ' + price + ' 元, 总计: ' + num * price;
//插值简写用``包含,表达式写在${express}中
res= `商品数量:${num},单价:${price},总计:${num*price}`;
标签函数
function show(strings, var1, var2) {
console.log(strings);
console.log(var1, var2);
let res = `<ul>商品信息:<li>${strings[0]}: ${var1} </li>
<li>${strings[1]}: ${var2}</li>
<li>${strings[2]}: ${var1 * var2}</li></ul>`;
console.log(res);
return res;
}
coust ul = show`商品数量${num}单价${price}总计${num*price}`;
解构赋值
对象解构
coust MAN = {
name = 'jack',
age = 18
}
//解构要求等号二边类型一致
({name,age} = {name:"jack",age:18} );
console.log(name,age);
//可以插入元素并设置默认值
({name,age,gender="man"} = {name:"jack",age:18});
console.log(name.age.gender);
//元素支持别名
({name:userName,age:useAge} = {name:"jack",age:18});
console.log(userName,userAge);
数组解构
//声明数组
coust arr = [1,2,3,4];
//等号左侧看做模板
let [num1.num2,num3,num4] = arr;
console.log(num1,num2,num3.num4);
let [a, [b, c], d] = [10, [20, 30], 40];
console.log(a, b, c, d);
//设置初始值
let [x, y, z = 999] = [100, 200];
console.log(x, y, z);
流程控制
分支
- 单分支
let a = 70
if (a > 60) console.log('大于60');
- 双分支
let a = 50;
if (a > 60) console.log('大于60');
else console.log('小于60');
- 多分支
let a = 90;
if (a >= 60 && a <= 80) console.log('在60~80之间');
elseif (a >= 81 && a <= 90 ) console.log('在80~90之间');
else console.log('不在60~90之间');
- switch 多分支
a = 50;
switch (true) {
case a >= 60 && a <= 80:
console.log('在60~80之间');break;
case a >= 81 && a <= 90:
console.log('在80~90之间');break;
default console.log('不在60~90之间);
}
//switch通常不去做区间判断,而是用于单值判断
let response = 'Success';
// 对于单值的字符器需要将格式统一化,例如全转为大写或小写
switch (response.toLowerCase()) {
case 'fail':
console.log('请求失败'); break;
case 'success':
console.log('请求成功'); break;
case 'error':
console.log('参数错误'); break;
default: console.log('未知错误');
}
- 三元运算符
a = 50;
console.log(a > 60 ? '大于60' : '小于60');
循环
- while 入口判断型
let a = 0;
while (a <= 5) {
console.log(a);
a++;
}
- do while 出口判断型
let a = 0;
do {
console.log(a);
a++;
}while(a <= 5);
//出口判断型即使不满足当前条件也会默认执行一次,例如 lat a = 6;
//do while 也会执行一次,输出6;
- for 循环
for (a = 0; a <= 5; a++) {
console.log(a);
}
- for循环和分支混合使用
for (a = 0; a <= 5; a++) {
if (a <= 3) console.log(a);
}
对象遍历
- for in
const man = {
name: "jack",
age: 18,
};
for (let key in man) {
console.log(`${key}=>${man[key]}`);
}
- for in
数组遍历
- for of
```html
const arr = [1, 2, 3, 4];
for (let value of arr) {
console.log(value);
}
- for of
```