今天所学心得、笔记
1、值传递与引用传递
// 值传递, 用aaa赋值给变量bbb,当aaa的值改变了,bbb值不会变
let aaa = 100;
let bbb= aaa; //值传递
console.log("aaa = %d, bbb = %d", aaa, bbb);
aaa = 200;
console.log("aaa = %d, bbb = %d", aaa, bbb);
//引用传递,改变的是变量的引用地址,地址里的值变了,
//所有引用该地址的变量,值都会改变
let obj_a = { a: 100, b: 200 };
console.log(obj_a);
let obj_b = obj_a;
console.log(obj_b);
// 更新obj_a
obj_a.a = 300;
console.log(obj_a);
// obj_b同步更新
console.log(obj_b);
2、数组和对象解构的常用方法与函数传参
数组解构
let [a1, b1, c1] = [1, 2, 3];
console.log(a1 , b1 , c1);
let [a2, b2, c2, d2=9, e2] = [1, 2, 3];
console.log(a2 , b2 ,c2, d2, e2);
let [a3, b3, ...c3] = [1, 2, 3, 4, 5];
console.log(a3 , b3 , c3);
let [, , d, , ,] = [1, 2, 3, 4, 5];
console.log(d);
对象解构
let {id, name} = {id:10, name:"手机"};
console.log(id, name);
({id, name} = {id:20, name:"笔记本"});
console.log(id, name);
//变量冲突,起别名
let email = "admin@php.cn";
let {role, email:uEmail} = {role:"user", email:"user@php.cn"};
console.log(email);
console.log(role, uEmail);
参数解构
// 数组传参
let sum = ([a, b]) => a +b;
console.log(sum([10, 20]));
// 对象传参
let getUser = ({name, email}) => [name, email];
console.log(getUser({name: "天蓬老师", email:"tp@php.cn"}));
3、call,apply,bind的区别与联系
function hello(name) {
this.name = name;
console.log(this.name);
}
const obj = {
name: "admin",
};
// 经典调用
console.log(hello("朱老师"));
// bind()不会立即执行,只返回一个函数声明
let f = hello.bind(obj, "天蓬老师");
console.log(f());
// call/apply立即执行
f = hello.call(obj, "灭绝老师");
console.log(f);
f = hello.apply(obj, ["西门老师"]);
console.log(f);
4、访问器属性的原理与实现过程
const product = {
data: [
{ name: "电脑", price: 1000, num: 10 },
{ name: "手机", price: 2000, num: 20 },
{ name: "相机", price: 3000, num: 30 },
],
get total() {
return this.data.reduce((t, c)=>(t += c.price * c.num), 0);
},
set setPrice(price) {
this.data[1].price = price;
},
};
console.log(product.total);
console.log(product.data[1].price);
product.setPrice = 8899;
console.log(product.data[1].price);
5、多分支与swithc
// if多分支
score = 80;
if (score >= 60 && score < 80) {
console.log("合格");
} else if (score >= 80 && score <= 100) {
console.log("学霸");
}
// 判断成绩是否合法
else if (score > 100 || score < 0) {
console.log("非法数据,请输入0--100之间的数值");
} else {
console.log("补考");
}
// switch判断
//switch是严格匹配, 在这个例程里()内一定要用true
score = 85;
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("非法数据,请输入0--100之间的数值");
break;
default:
console.log("补考");
}
6、三元运算
// 三元运算符,条件? true : false
// 相当于简单的if()else()语句,在双分支的情况下,简化代码
//有什么限制,还不知道???猜想的限制可能是,应用于双分之以上的条件判断,
//会导致代码可读性非常差
score = 80;
console.log(score >= 60 ? "及格" : "补考");