js基础速成11-解构与展开

解构与展开

解构是一种将数组和对象解包并赋值给不同变量的方式。

解构数组

const numbers = [1, 2, 3];
let [numOne, numTwo, numThree] = numbers;

console.log(numOne, numTwo, numThree);
1 2 3
const names = ['Asabeneh', 'Brook', 'David', 'John'];
let [firstPerson, secondPerson, thirdPerson, fourthPerson] = names;

console.log(firstPerson, secondPerson, thirdPerson, fourthPerson);
Asabeneh Brook David John
const scientificConstants = [2.72, 3.14, 9.81, 37, 100];
let [e, pi, gravity, bodyTemp, boilingTemp] = scientificConstants;

console.log(e, pi, gravity, bodyTemp, boilingTemp);
2.72 3.14 9.81 37 100
const fullStack = [
  ['HTML', 'CSS', 'JS', 'React'],
  ['Node', 'Express', 'MongoDB']
];
const [frontEnd, backEnd] = fullStack;

console.log(frontEnd);
console.log(backEnd);
["HTML", "CSS", "JS", "React"]
["Node", "Express", "MongoDB"]

如果我们想跳过数组中的某个值,可以使用额外的逗号。逗号有助于省略特定索引的值。

const numbers = [1, 2, 3];
let [numOne, , numThree] = numbers; // 2 被省略

console.log(numOne, numThree);
1 3
const names = ['Asabeneh', 'Brook', 'David', 'John'];
let [, secondPerson, , fourthPerson] = names; // 第一和第三人被省略

console.log(secondPerson, fourthPerson);
Brook John

我们可以使用默认值来处理数组某个索引的值为未定义的情况:

const names = [undefined, 'Brook', 'David'];
let [
  firstPerson = 'Asabeneh',
  secondPerson,
  thirdPerson,
  fourthPerson = 'John'
] = names;

console.log(firstPerson, secondPerson, thirdPerson, fourthPerson);
Asabeneh Brook David John

我们不能为数组中的所有元素赋值。我们可以解构前几个元素,并使用展开运算符(…)获取剩余元素作为数组。

const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let [num1, num2, num3, ...rest] = nums;

console.log(num1, num2, num3);
console.log(rest);
1 2 3
[4, 5, 6, 7, 8, 9, 10]

在迭代中解构

const countries = [['Finland', 'Helsinki'], ['Sweden', 'Stockholm'], ['Norway', 'Oslo']];

for (const [country, city] of countries) {
  console.log(country, city);
}
Finland Helsinki
Sweden Stockholm
Norway Oslo
const fullStack = [
  ['HTML', 'CSS', 'JS', 'React'],
  ['Node', 'Express', 'MongoDB']
];

for(const [first, second, third] of fullStack) {
  console.log(first, second, third);
}
HTML CSS JS
Node Express MongoDB

解构对象

当我们解构对象时,解构变量的名称必须与对象的键或属性完全相同。见下例。

const rectangle = {
  width: 20,
  height: 10,
  area: 200
};
let { width, height, area, perimeter } = rectangle;

console.log(width, height, area, perimeter);
20 10 200 undefined

在结构时重命名

const rectangle = {
  width: 20,
  height: 10,
  area: 200
};
let { width: w, height: h, area: a, perimeter: p } = rectangle;

console.log(w, h, a, p);
20 10 200 undefined

如果在对象中找不到键,变量将被赋值为未定义。有时键可能不在对象中,这种情况下我们可以在声明时给出默认值。见下例。

const rectangle = {
  width: 20,
  height: 10,
  area: 200
};
let { width, height, area, perimeter = 60 } = rectangle;

console.log(width, height, area, perimeter); //20 10 200 60
//让我们修改对象:将宽度改为30,周长改为80
const rectangle = {
  width: 30,
  height: 10,
  area: 200,
  perimeter: 80
};
let { width, height, area, perimeter = 60 } = rectangle;
console.log(width, height, area, perimeter); //30 10 200 80

将解构作为函数参数。让我们创建一个接收矩形对象并返回矩形周长的函数。

没有解构的对象参数

// 没有解构
const rect = {
  width: 20,
  height: 10
};
const calculatePerimeter = rectangle => {
  return 2 * (rectangle.width + rectangle.height);
};

console.log(calculatePerimeter(rect)); // 60
//有解构
//另一个例子
const person = {
  firstName: 'Asabeneh',
  lastName: 'Yetayeh',
  age: 250,
  country: 'Finland',
  job: 'Instructor and Developer',
  skills: [
    'HTML',
    'CSS',
    'JavaScript',
    'React',
    'Redux',
    'Node',
    'MongoDB',
    'Python',
    'D3.js'
  ],
  languages: ['Amharic', 'English', 'Suomi(Finnish)']
};
// 让我们创建一个给出关于个人对象信息的函数,不使用解构

const getPersonInfo = obj => {
  const skills = obj.skills;
  const formattedSkills = skills.slice(0, -1).join(', ');
  const languages = obj.languages;
  const formattedLanguages = languages.slice(0, -1).join(', ');

  personInfo = `${obj.firstName} ${obj.lastName} lives in ${obj.country}. He is  ${
    obj.age
  } years old. He is an ${obj.job}. He teaches ${formattedSkills} and ${
    skills[skills.length - 1]
  }. He speaks ${formattedLanguages} and a little bit of ${languages[2]}.`;

  return personInfo;
};

console.log(getPersonInfo(person));

使用解构的对象参数

const calculatePerimeter = ({ width, height }) => {
  return 2 * (width + height);
};

console.log(calculatePerimeter(rect)); // 60
// 让我们创建一个给出关于个人对象信息的函数,使用解构
const getPersonInfo = ({
  firstName,
  lastName,
  age,
  country,
  job,
  skills,
  languages
}) => {
  const formattedSkills = skills.slice(0, -1).join(', ');
  const formattedLanguages = languages.slice(0, -1).join(', ');

  personInfo = `${firstName} ${lastName} lives in ${country}. He is ${age} years old. He is an ${job}. He teaches ${formattedSkills} and ${
    skills[skills.length - 1]
  }. He speaks ${formattedLanguages} and a little bit of ${languages[2]}.`;

  return personInfo;
};
console.log(getPersonInfo(person));
/*
Asabeneh Yetayeh lives in Finland. He is  250 years old. He is an Instructor and Developer. He teaches HTML, CSS, JavaScript, React, Redux, Node, MongoDB, Python and D3.js. He speaks Amharic, English and a little bit of Suomi(Finnish)
*/

在迭代中解构对象

const todoList = [
  {
    task: 'Prepare JS Test',
    time: '4/1/2020 8:30',
    completed: true
  },
  {
    task: 'Give JS Test',
    time: '4/1/2020 10:00',
    completed: false
  },
  {
    task: 'Assess Test Result',
    time: '4/1/2020 1:00',
    completed: false
  }
];

for (const { task, time, completed } of todoList) {
  console.log(task, time, completed);
}
Prepare JS Test 4/1/2020 

8:30 true
Give JS Test 4/1/2020 10:00 false
Assess Test Result 4/1/2020 1:00 false

展开或剩余运算符

当我们解构数组时,使用展开运算符(…)获取其余元素作为数组。此外,我们使用展开运算符将数组元素展开到另一个数组中。

展开运算符获取数组剩余元素

const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let [num1, num2, num3, ...rest] = nums;

console.log(num1, num2, num3);
console.log(rest);
1 2 3
[4, 5, 6, 7, 8, 9, 10]
const countries = [
  'Germany',
  'France',
  'Belgium',
  'Finland',
  'Sweden',
  'Norway',
  'Denmark',
  'Iceland'
];

let [gem, fra, , ...nordicCountries] = countries;

console.log(gem);
console.log(fra);
console.log(nordicCountries);
Germany
France
["Finland", "Sweden", "Norway", "Denmark", "Iceland"]

展开运算符复制数组

const evens = [0, 2, 4, 6, 8, 10];
const evenNumbers = [...evens];

const odds = [1, 3, 5, 7, 9];
const oddNumbers = [...odds];

const wholeNumbers = [...evens, ...odds];

console.log(evenNumbers);
console.log(oddNumbers);
console.log(wholeNumbers);
[0, 2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]
[0, 2, 4, 6, 8, 10, 1, 3, 5, 7, 9]
const frontEnd = ['HTML', 'CSS', 'JS', 'React'];
const backEnd = ['Node', 'Express', 'MongoDB'];
const fullStack = [...frontEnd, ...backEnd];

console.log(fullStack);
["HTML", "CSS", "JS", "React", "Node", "Express", "MongoDB"]

展开运算符复制对象

我们可以使用展开运算符复制对象。

const user = {
  name: 'Asabeneh',
  title: 'Programmer',
  country: 'Finland',
  city: 'Helsinki'
};

const copiedUser = { ...user };
console.log(copiedUser);
{name: "Asabeneh", title: "Programmer", country: "Finland", city: "Helsinki"}

在复制时修改或更改对象

const user = {
  name: 'Asabeneh',
  title: 'Programmer',
  country: 'Finland',
  city: 'Helsinki'
};

const copiedUser = { ...user, title: 'instructor' };
console.log(copiedUser);
{name: "Asabeneh", title: "instructor", country: "Finland", city: "Helsinki"}
使用箭头函数的展开运算符

每当我们希望编写一个接受无限数量参数的箭头函数时,我们使用展开运算符。如果我们将展开运算符作为参数,调用函数时传入的参数将变为数组。

const sumAllNums = (...args) => {
  console.log(args);
};

sumAllNums(1, 2, 3, 4, 5);
[1, 2, 3, 4, 5]
const sumAllNums = (...args) => {
  let sum = 0;
  for (const num of args) {
    sum += num;
  }
  return sum;
};

console.log(sumAllNums(1, 2, 3, 4, 5));
15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Code王工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值