Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:
赋值分为值传递和引用传递,值传递用于原始类型,string number bool 值传递更新相同的变量不影响同类引用传递是用于引用类型 object array更新一个值以后相关联的也会改变;
相应实例如下所示:
值传递:
let a = 1;
let b = a;
a = 2;
// 更新a不影响b的值
console.log("a=%d,b=%d", a, b);
//引用传递
let obj1 = { a: 12, b: 13, c: 14 };
let obj2 = obj1;
console.log(obj1, obj2);
obj1.a = 15;
console.log(obj1, obj2);
运行结果:
数组对象的解构主要是为了方便简化赋值,如下代码所示:
let [a, b, c] = [1, 2, 3];
console.log(a, b, c);
[a, b] = [1, 2, 3];
console.log(a, b);
[a, b, c, d = "xxxx"] = [1, 2, 3];
console.log(a, b, c, d);
[a, b, ...c] = [1, 2, 3, 4, 5];
console.log(a, b, c);
[, , a, ,] = [1, 2, 3, 4, 5];
console.log(a);
let x = 1,
y = 2,
t;
console.log("x = %d, y = %d", x, y);
// t = x;
// x = y;
// y = t;
// console.log("x = %d, y = %d", x, y);
[y, x] = [x, y];
console.log("x = %d, y = %d", x, y);
// 2. 对象解构
let { id, name } = { id: 10, name: "手机" };
console.log(id, name);
// 属性名与变量名必须一一对应,顺序无所谓
({ name, id } = { id: 10, name: "手机" });
console.log(id, name);
单分支控制用if(条件){代码} else{代码}
也可以用三元表达式,三元表达式的写法:判断条件?true成功的结果:fail失败的结果;
三元表达式只能用来判断单一条件的语句,多分支判断可以用if(条件){代码} else if(条件){代码}else{代码}
来判断,多分支还可以用switch来简化,代码结构:switch(true代码执行是否执行) {case 条件:代码段;break;
case 条件:代码;break;default:代码;}
。
代码如下所示:
if (score >= 60) {
console.log("及格");
// 默认分支
} else {
console.log("补考");
}
// 多分支
score = 98;
if (score >= 60 && score < 80) {
console.log("合格");
} else if (score >= 80 && score <= 100) {
console.log("学霸");
}
// 判断成绩是否合法
else if (score > 100 || score < 0) {
console.log("非法数据");
} else {
console.log("补考");
}
// switch来简化多分支
// switch是严格匹配
score = 198;
switch (true) {
case score >= 60 && score < 80:
console.log("合格");
break;
case score >= 80 && score <= 100:
console.log("学霸");
break;
// 判断成绩是否合法
case score > 100 || score < 0:
console.log("非法数据");
break;
default:
console.log("补考");
}
// switch用在单值判断
let response = "Success";
switch (response.toLowerCase()) {
case "fail":
console.log("请求失败");
break;
case "success":
console.log("请求成功");
break;
default:
console.log("未知错误");
}