Javascript 解構賦值,將屬性/值從物件/陣列中取出,賦值給其他變數

書院二層樓發表於2020-10-04
概念:解構賦值語法是一種 Javascript 表示式。通過解構賦值, 可以將屬性/值從物件/陣列中取出,賦值給其他變數。
var a, b, rest;
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2

[a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(a); // 1
console.log(b); // 2
console.log(rest); // [3, 4, 5]

({ a, b } = { a: 1, b: 2 });
console.log(a); // 1
console.log(b); // 2


({a, b, ...rest} = {a: 1, b: 2, c: 3, d: 4});
console.log(a); // 1
console.log(b); // 2
console.log(rest); // {c: 3, d: 4}




應用:使用解構賦值交換兩個變數的值。
var a = 3;
var b = 8;

[a, b] = [b, a];
console.log(a); // 8
console.log(b); // 3


應用:解析一個從函式返回的陣列
function fn() {
  return [6, 8];
}

var a, b; 
[a, b] = fn(); 
console.log(a); // 6
console.log(b); // 8

應用:忽略不感興趣的值
function f() {
  return [6, 7, 8];
}

var [a, , b] = f();
console.log(a); // 6
console.log(b); // 8

應用:將剩餘陣列賦值給一個變數
var [a, ...b] = [6, 7, 8];
console.log(a); // 6
console.log(b); // [7, 8]


應用:物件結構賦值
var people = [
  {
    name: 'Mike Smith',
    family: {
      mother: 'Jane Smith',
      father: 'Harry Smith',
      sister: 'Samantha Smith'
    },
    age: 35
  },
  {
    name: 'Tom Jones',
    family: {
      mother: 'Norah Jones',
      father: 'Richard Jones',
      brother: 'Howard Jones'
    },
    age: 25
  }
];

for (var {name: n, family: {father: f}} of people) {
  console.log('Name: ' + n + ', Father: ' + f);
}

// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"

 

相關文章