值传递方式
赋值
- 值传递: 原始类型,string,number,bool
let a = 1;
let b = a;
//更新a的值为2
a = 2;
//输出b = 1,更新a的值,并不会影响b的值
b = 1;
let obj1 {
id:1,
name:'iphone',
let obj2 = obj1;
//更新obj1的属性
obj1.name = 'vivo';
//输出obj2;name也变成vivo,引用传递会同步更新
obj2.name = 'vivo';
}
传参
- 传参时,不论什么类型,都是”值传递”
- 入参: 调用函数是传入的参数,简称:”入参”
let f1 = (x) => (x = 10);
let m = 5;
f1(m);
console.log(m);
//输出m=5 函数中对参数的更新,并不会影响到入参
const f2 = x => (x.a = 10);
let o = { a: 1, b: 2 };
console.log(o);
f2(o);
console.log(o);
//输出{a: 10,b: 2}
// 看上去函数中对于o.a的更新生效,实际上仍是值传递
解构赋值
数组
let [a, b, c] = [1, 2, 3];
console.log(a, b, c);
//输出 1,2,3
let x = 1,
y = 2;
//x,y的值对换
[x,y] = [y,x];
对象
let { id, name } = { id: 10, name: "手机" };
//可以写成let {name,id}
参数解构
// 数组传参
let sum = ([a, b]) => a + b;
console.log(sum([10, 20]));
// 对象传参
let getUser = ({ name, email }) => [name, email];
console.log(getUser({ email: "tp@php.cn", name: "天蓬老师" }));
bind,call,apply函数
bind 不会立即执行,只返回一个函数声明
function hello(name) {
this.name = name;
console.log(this.name);
}
let f = hello.bind(obj, "天蓬老师");
//输出的是hello的函数声明
console.log(f());
call/apply立即执行
function getName(name) {
this.name = name;
console.log(name);
}
let f = getName.call(name, "jack");
//apply需要是数组
let f1 = getName.apply(name, ["Tom"]);
访问器属性
const product = {
data: [
{ name: "电脑", price: 5000, num: 5 },
{ name: "手机", price: 4000, num: 10 },
{ name: "相机", price: 8000, num: 3 },
],
//get用来获取参数
get total() {
return this.data.reduce((t, c) => (t += c.price * c.num), 0);
},
//set用来修改参数
set setPrice(price) {
this.data[1].price = price;
},
};
console.log("总金额 :", product.total);
product.setPrice = 9988;
运算符
swicth case
let response = "Success";
switch (response.toLowerCase()) {
case "fail":
console.log("请求失败");
break;
case "success":
console.log("请求成功");
break;
default:
console.log("未知错误");
}
三元运算符
- 三元运算符用来简化双分支
- 格式:条件 ? true : false
score = 80;
console.log(score >= 60 ? "及格" : "补考");