let [a, b = 2] = [3] a // 3 b // 2,因为b没有对应值,所以是undefined,使用默认值
let [a, b = 2] = [3, 4] a //3 b //4 数组对应对值有没有?如果没有(数组对没有指undefined)就使用默认值,如果有就使用对应值
let [a=2, b=3] = [undefined, null] a //2 b //null let [a=1, b=a] = [2] a //2 b //2,因为b没有对应值,所以是undefined,使用默认值,此时a的默认值为2
对象的解构赋值
前置知识
1 2 3 4 5 6 7 8 9 10 11 12 13 14
let [name, age] = ["hunger", 3]; let p1 = { name, age }; //等同于 let p2 = { name: name, age: age }; 解构范例;
let { name, age } = { name: "jirengu", age: 4 }; name; //‘jirengu’ age; //4 以上代码等同于;
let name; let age; ({ name: name, age: age } = { name: "jirengu", age: 4 });
默认值
1 2 3
let { x, y = 5 } = { x: 1 }; x; //1 y; //5
函数解构
1 2 3 4 5 6 7 8 9 10 11
functionadd([x = 1, y = 2]) { return x + y; } add(); //Error add([2]); //4 add([3, 4]); //7
functionsum({ x, y } = { x: 0, y: 0 }, { a = 1, b = 1 }) { return [x + a, y + b]; } sum({ x: 1, y: 2 }, { a: 2 }); //[3, 3]
作用
1 2 3 4 5 6 7
let [x, y] = [1, 2]; [x, y] = [y, x] x //2 y // 1 functionajax({url, type=‘GET’}){ } ajax({url: ‘http://localhost:3000/getData’})
字符串,数组,对象
字符串
多行字符串
1 2 3 4 5
let str = ` Hi, This is jirengu.com. You can study frontend here. `;
字符串模板
1 2 3 4 5 6 7
let website = "jirengucom"; let who = "You"; let str = `Hi This is ${website}. ${who} can study frontend here `; //${},可以替换变量
1 2 3 4 5
var data = [1, 2, 3, 4]; var liArr = data.map((v) =>`<li>${v}</li>`).join(""); var html = `<ul>${liArr}</ul>`; console.log(html); //"<ul><li>1</li><li>2</li><li>3</li><li>4</li></ul>"
数组
扩展运算符...
主要作用是将数组或对象进行展开.
对象中的扩展运算符(…)用于取出参数对象中的所有可遍历属性,拷贝到当前对象之中
1 2 3 4 5 6 7
var a = [1, 2]; console.log(...a); // 1, 2,这三个点相当于脱壳,把数组的壳拿掉 var b = [...a, 3]; b; // [1, 2, 3]
var c = b.concat([4, 5]); //b拼接[4,5]变成[1,2,3,4,5] var d = [...b, 4, 5]; //直接把脱壳后的1,2,3放入数组中