ES6 解構對象和數組


1.解構對象

let saveFiled = {
  extension: "jpg",
  name:"girl",
  size:14040
};

ES5
function fileSammary(file){
  return `${file.name}.${file.extension}的總大小是${file.size}`;
}
console.log(fileSammary(saveFiled));


ES6
function fileSammary({name,extension,size}){
  return `${name}.${extension}的總大小是${size}`;
}

console.log(fileSammary(saveFiled));

2.解構數組

1.返回數組第一位數值
const names = ["Henry","Bucky","Emily"];

ES5
console.log(names[0])

ES6
const [name1,name2,name3] = names;
console.log(name1)

2.返回數組個數
ES5
console.log(names .length)

ES6
const { length } = names
console.log(length)

3.結合展開運算符
const [name,...rest] = names;
console.log(name, rest);

4.對象數組
const people = [
  {name:"Henry",age:20},
  {name:"Bucky",age:25},
  {name:"Emily",age:30}
];

ES5
var age = people[0].age;
console.log(age);

ES6
const [age] = people;
console.log(age)   //{name:"Henry",age:20}
const [{age}] = people;
console.log(age)   // 20

5. 使用場景 將數組轉化為對象
const points = [
  [4, 5],
 [10, 1],
 [0, 40]
]
// 期望數據格式
[
  {x:4,y:5},
  {x:10,y:1},
  {x:0,y:40}
]

ES6
let newPoints = points.map(pair => {
  // const x = pair[0];
  // const y = pair[1];
  const [x,y] = pair;
  return {x,y}
})

let newPoints = points.map(([x, y]) => {
  // const x = pair[0];
  // const y = pair[1];
  // const [x,y] = pair;
  return { x, y }
})

console.log(newPoints)

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM