Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
单分支:仅当表达式计算结果为真时, 才执行代码块;
let age = 29;
if (age >= 18) {
console.log("允许观看");
}
根据条件,有2条不同的执行语句;
一般样式:
age = 15;
if (age >= 18) {
console.log("允许观看");
} else {
console.log("少儿不宜");
}
“语法糖”样式:
age = 30;
console.log(age >= 18 ? "允许观看" : "少儿不宜");
有多个条件的执行语句;
if…else写法:
age = 12;
if (age >= 18 && age < 35) {
console.log("允许单独收看");
} else if (age >= 45 && age < 60) {
console.log("建议二人收看");
} else if (age >= 60 && age < 120) {
console.log("建议家人陪同收看");
} else if (age >= 120 || age <= 3) {
console.log("非法年龄");
} else {
console.log("少儿不宜观看");
}
Switch写法:
age = 46;
// * 区间判断, 使用 true
switch (true) {
case age >= 18 && age < 35:
console.log("允许单独收看");
break;
case age >= 45 && age < 60:
console.log("建议二人收看");
break;
case age >= 60 && age < 120:
console.log("建议家人陪同收看");
break;
case age >= 120 || age <= 3:
console.log("非法年龄");
break;
default:
console.log("少儿不宜观看");
break;
}
循环三条件
a. 初始条件: 数组索引的引用 ( i = 0 )
b. 循环条件: 为真才执行循环体 ( i < arr.length )
c. 更新条件: 必须要有,否则进入死循环 ( i++ )
const colors = ["red", "green", "blue"];
i = 0;
while (i < length) {
console.log(colors[i]);
i++;
}
const colors = ["red", "green", "blue"];
i = 0;
do {
console.log(colors[i]);
i++;
} while (i < length);
const colors = ["red", "green", "blue"];
for (let i = 0, length = colors.length; i < length; i++) {
console.log(colors[i]);
}
const colors = ["red", "green", "blue"];
for (let item of colors) {
console.log(item);
}
const colors = ["red", "green", "blue"];
const obj = { a: 1, b: 2, c: 3, say: function () {} };
//遍历对象
for (let key in obj) {
console.log(obj[key]);
}
//遍历数组
for (let key in colors) {
console.log(colors[key]);
}
f = (a, b = 0) => a + b;
console.log(f(1));
console.log(f(1, 5));
f = (a, b, c, ...arr) => `${a},${b},${c},${arr}`;
console.log(f(1, 2, 3, 4, 5, 6, 7, 8));
// 计算任何数量的数据之和
f = (...arr) => arr.reduce((a, b) => a + b);
console.log(f(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
// * 数组
f = () => [1, 2, 3];
console.log(f());
// * 对象: 模块
f = () => ({ a: 1, b: 2, get: function () {} });
console.log(f());
let name = "Harvey";
user = {
name,
getName() {
return this.name;
},
};
console.log(user.getName());
console.log(`Hello world`);
模板字面量中,可以使用”插值”(变量,表达式),可以解析变量
let name = "Harvey";
console.log("Hello " + name);
console.log(`${10 < 20 ? "大于" : "小于"}`);
就是使用”模板字面量’为参数的函数;
function sum(strings, ...args) {
console.log(strings);
console.log(args);
console.log(`[${args.join()}]之和是: ${args.reduce((a, b) => a + b)}`);
}
//调用
sum`计算多个数的和:${1}${2}${3}${4}${5}${6}${7}`;