1. 解构赋值

  • 解构赋值 是一种特殊的语法,它使我们可以将数组或对象“拆包”至一系列变量中。有时这样做更方便。
    解构操作对那些具有很多参数和默认值等的函数也很奏效。

  • 它“拆开”了数组或对象,将其中的各元素复制给一些变量。原来的数组或对象自身没有被修改。

let arr = ['john', 'smith'];
let [ firstname, surname] = arr;
alert(firstname); // john
alert(surname); // smith
  • 与split函数使用(或其他返回值为数组的函数)
let [ firstname, surname] = 'John Smith'.split(' ');
alert(firstname); // john
alert(surname); // smith
  • 结构并不是破坏 (下面的代码等价)
// let [firstName, surname] = arr;
let firstName = arr[0];
let surname = arr[1];
  • 可以丢弃掉不想要的元素 (可以通过添加额外的逗号来丢弃数组中不想要的元素)
//丢弃第二个元素
 let [firstName, , title] = ['Julius', 'Caesar', 'Consul']
 alert(title) //Consul
 //在上面的代码中,数组的第二个元素被跳过了,第三个元素被赋值给了 title 变量。数组中剩下的元素也都被跳过了(因为在这没有对应给它们的变量)。
  • 我们可以将其与任何可迭代对象一起使用,而不仅限于数组:
	let [a, b, c] = 'abc';
   alert(b); //b
   let [one, two, three] = new Set([1,2,3])
   alert(two) //2

迭代只是循环的一种方式,循环具体有三种for,while,do-while,而迭代指的是循环输出一个列表或者数组的所有元素

  • 与 .entries() 方法进行循环操作 来遍历一个对象的“键—值”对:
 let user = {
        name:'John',
        age: 30
    };

    // 使用for循环遍历 键-值对
    for(let [key, value] of Object.entries(user)){
        console.log(key, value);
        // console.log(`${key}:${value}`) 
        //name John
        //age 30
    }
  • 用于 Map 的类似代码更简单,因为 Map 是可迭代的
 let user = new Map();
    user.set('name', 'john');
    user.set('age', '30');
    // Map 是以 [key, value] 对的形式进行迭代的,非常便于解构
    for(let[key, value] of user){
        alert(`${key}:${value}`);
    }
数组解构赋值
// 一一对应
let [a, b, c, d, e, f] = ['张飞', '赵云', '关羽', '张辽', '许褚', '典韦']
console.log(a, b, c, d, e, f);

// 变量多 值少
let [a, b, c, d, e, f, g, h, i, j, k,l] = ['张飞', '赵云', '关羽', '张辽', '许褚', '典韦'];
console.log( a, b, c, d, e, f, g, h, i, j, k, l );
// 张飞 赵云 关羽 张辽 许褚 典韦 undefined undefined undefined undefined undefined undefined

// 变量少值多
let [a, b, c] = ['张飞', '赵云', '关羽', '张辽', '许褚', '典韦'];
console.log( a, b, c );
//张飞 赵云 关羽

// 按需取值
let [, , a, b, , c] = ['张飞', '赵云', '关羽', '张辽', '许褚', '典韦']
console.log( a, b, c );
//关羽 张辽 典韦

//其余的 ‘…’
//如果数组比左边的列表长,那么“其余”的数组项会被省略
//如果我们还想收集其余的数组项 —— 我们可以使用三个点 "..." 来再加一个参数以获取其余数组项:
let[, a, b, ...rest] = ['张飞', '赵云', '关羽', '张辽', '许褚', '典韦'];
	console.log(a, b, c);
// 赵云 关羽 (3) ['张辽', '许褚', '典韦']
//不一定要使用变量名 rest,我们也可以使用任何其他的变量名。只要确保它前面有三个点,并且在解构赋值的最后一个参数位置上就行了:

// 默认值 
//默认值可以是更加复杂的表达式,甚至可以是函数调用。不过,这些表达式或函数只会在这个变量未被赋值的时候才会被计算。

举个例子,我们使用了 prompt 函数来提供两个默认值
let [name = prompt('name?'), surname = prompt('surname?')] = ["Julius"];
alert(name);    // Julius(来自数组)
alert(surname); // 你输入的值
//请注意:prompt 将仅针对缺失值(surname)运行。
  • 对象解构赋值

let options = {
	title: 'Menue',
	width: 100,
	height: 200
};
let {title, width, height} = options;
alert(width); //100
//属性 options.title、options.width 和 options.height 值被赋给了对应的变量。
// 改变 let {...} 中元素的顺序 不影响
let {height, width, title} = { title: "Menu", height: 200, width: 100 }

 // 把对象解开解构赋值给变量
 // 用冒号改名字
 let options = {
  title: "Menu",
  width: 100,
  height: 200
};

// { sourceProperty: targetVariable }
let {width: w, height: h, title} = options;
// width -> w
// height -> h
// title -> title
alert(title);  // Menu
alert(w);      // 100
alert(h);      // 200
//冒号的语法是“从对象中什么属性的值:赋值给哪个变量”。上面的例子中,属性 width 被赋值给了 w,属性 height 被赋值给了 h,属性 title 被赋值给了同名变量。

//对于可能缺失的属性,我们可以使用 "=" 设置默认值
let options = {
  title: "Menu"
};
let {width = 100, height = 200, title} = options;
alert(title);  // Menu
alert(width);  // 100
alert(height); // 200

//就像数组或函数参数一样,默认值可以是任意表达式甚至可以是函数调用。它们只会在未提供对应的值时才会被计算/调用。
//在下面的代码中,prompt 提示输入 width 值,但不会提示输入 title 值:
let options = {
  title: "Menu"
};
let {width = prompt("width?"), title = prompt("title?")} = options;
alert(title);  // Menu
alert(width);  // (prompt 的返回值)

// 将等号和:结合使用
let options = {
  title: "Menu"
};
let {width: w = 100, height: h = 200, title} = options;
alert(title);  // Menu
alert(w);      // 100
alert(h);      // 200

// 剩余模式
let options = {
  title: "Menu",
  height: 200,
  width: 100
};

// title = 名为 title 的属性
// rest = 存有剩余属性的对象
let {title, ...rest} = options;
// 现在 title="Menu", rest={height: 200, width: 100}
alert(rest.height);  // 200
alert(rest.width);   // 100

//嵌套解构
let options = {
  size: {
    width: 100,
    height: 200
  },
  items: ["Cake", "Donut"],
  extra: true
};

// 为了清晰起见,解构赋值语句被写成多行的形式
let {
  size: { // 把 size 赋值到这里
    width,
    height
  },
  items: [item1, item2], // 把 items 赋值到这里
  title = "Menu" // 在对象中不存在(使用默认值)
} = options;

alert(title);  // Menu
alert(width);  // 100
alert(height); // 200
alert(item1);  // Cake
alert(item2);  // Donut

//我们可以用一个对象来传递所有参数,而函数负责把这个对象解构成各个参数:
let options = {
  title: "My menu",
  items: ["Item1", "Item2"]
};
// ……然后函数马上把对象解构成变量
function showMenu({title = "Untitled", width = 200, height = 100, items = []}) {
  // title, items – 提取于 options,
  // width, height – 使用默认值
  alert( `${title} ${width} ${height}` ); // My Menu 200 100
  alert( items ); // Item1, Item2
}
showMenu(options);


function person ( {uname, age, sex} ) {
			// let uname = obj.uname;
			// let age = obj.age;
			// let sex = obj.sex;
console.log(`我叫${uname}今年${age}岁是${sex}性`);
}
person( {uname : '阿飞', age : 22, sex : '男'} )
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐