js ES6解构赋值
程序员文章站
2022-07-02 10:40:45
...
js ES6解构赋值
交换变量的值:
let x = 1;
let y = 2;
[x,y] = [y,x];
console.log(x,y);
//1用一个中间变量
let z = x;
x = y;
y = z;
console.log(x,y);
// 2异或
x = x^y;
y = x^y;
x = x^y;
console.log(x,y);
// 3. 算术运算符 - +
x = x + y;
y = x - y;
x = x - y;
console.log(x,y);
从函数返回多个值
function fn() {
return [1, 2, 3];
}
let [a, b, c] = fn();
console.log(b);
let c = fn();
let a = c[0];
let b = c[1];
let e = c[2];
函数参数的定义
function a(arg1, arg2, arg3, arg4, arg5, arg6) {}
a(arr[0], 2, 3, 4, 5, 6);
let arr = [1, 2, 3, 4, 5, 6]
function a([arg1, arg2, arg3, arg4, arg5, arg6]){
console.log(arg6);
}
a(arr);
提取 JSON 数据 主要是做数据传输 前端传数据给后端 后端要传数据给前面
let obj = { a: "1", b: "2" };
console.log(obj.a);
//后端来的数据
let obj = {
title: "恭喜XXX获奖!",
description: "北京什么什么什么时间!xxx中了大奖!",
};
let { title, description: des } = obj;
let title = obj.title;
let description = obj.description;
解构赋值 :
赋值运算符的扩展
它是专门对数组和对象进行模式匹配
使代码比较的简洁
对数组
let [a,b,c] = [1,2,3]
a 1 b 2 c 3
1.可以嵌套
let [a, b, c, [d, [e]]] = [1, 2, 3, [1, [2]]];
console.log(e);
2.可忽略
let [a,,b] = [1,2,3];
console.log(a);//a:1,b:3
3.不完全解构
let [a = 1, b] = [];
console.log(a);
console.log(b);
4.剩余运算符
let [a, ...b] = [1, 2, 3];
console.log(a);
console.log(b);
5. 解构默认
let [a = 2] = [undefined];
console.log(a);
let [a = 3, b = a] = []; //a 3 b 3
let [a = 3, b = a] = [2]; // a 2 b 2
let [a = 3, b = a] = [4, 5]; // a4 b 5
console.log(a);
console.log(b);
对字符串:
let [a, b, c, d, e] = "剩余运算符";
console.log(a, b, c, d, e);
let [foo] = 1;
会出现报错的情况
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};
针对 对象
let { a, b } = { a: "aaaa", b: "bbbb" };
console.log(a, b);
1.可以嵌套
let obj = { a: ["bbbb", { c: "cccc" }] };
let {
a: [b, { c }]
} = obj;
console.log(b);
2. 可忽略
let {a,} = { a: "aaaa", b: "bbbb" };
console.log(a);
3.不完全解构 解构默认
let {a = 10,b = 5} = { };
console.log(a);
function add(a = 0,b = 0){
console.log(a + b);
}
add();
4.剩余运算符
let { a, ...b } = { a: "aaaa", b: "bbbb", c: "cccc" };
console.log(b);
上一篇: 关于JavaScript 基础总结
下一篇: Tomcat 生产服务器性能优化