来源于Jonas老师的课程代码

const game = {
  team1: 'Bayern Munich',
  team2: 'Borrussia Dortmund',
  players: [
    [
      'Neuer',
      'Pavard',
      'Martinez',
      'Alaba',
      'Davies',
      'Kimmich',
      'Goretzka',
      'Coman',
      'Muller',
      'Gnarby',
      'Lewandowski',
    ],
    [
      'Burki',
      'Schulz',
      'Hummels',
      'Akanji',
      'Hakimi',
      'Weigl',
      'Witsel',
      'Hazard',
      'Brandt',
      'Sancho',
      'Gotze',
    ],
  ],
  score: '4:0',
  scored: ['Lewandowski', 'Gnarby', 'Lewandowski', 'Hummels'],
  date: 'Nov 9th, 2037',
  odds: {
    team1: 1.33,
    x: 3.25,
    team2: 6.5,
  },
};

// 1. 为每支球队分别创建一个球员数组(变量名:players1 和 players2)。
const [players1, players2] = game.players;
console.log(players1, players2);
// 2. 每个球员数组中,第一个球员是守门员,其余为场上球员。
//    为team 1创建:
//    - 一个变量 gk,保存守门员姓名;
//    - 一个数组 fieldPlayers,保存剩余 10 名场上球员。
const [gk, ...fieldPlayers] = players1;
console.log(gk, fieldPlayers);
console.log(gk, fieldPlayers);

// 3. 创建一个数组 allPlayers,包含两支球队的所有 22 名球员。
const allplayers = [...players1, ...players2];
console.log(allplayers);
// 4. 比赛期间,team 1使用了 3 名替补球员。
// 因此,创建一个新数组 players1Final,
// 包含拜仁原始球员外加 'Thiago'、'Coutinho' 和 'Perisic'。
const players1Final = [...players1, 'Thiago', 'Coutinho', 'Perisic'];
console.log(players1Final);
// 5. 基于 game.odds 对象,创建三个变量:team1、draw、team2,分别对应三种赔率。
const { team1, x: draw, team2 } = game.odds; //相当于const team1 = game.odds.team1;
//const { odds: { team1, x: draw, team2 } } = game;
console.log(team1, draw, team2);
// 6. 编写一个函数 printGoals,该函数接收任意数量的球员姓名(不是数组),
//    在控制台逐行打印每位球员,并输出总进球数(即传入的球员姓名个数)。
// 第一次调用使用球员 'Davies', 'Muller', 'Lewandowski', 'Kimmich';
// 第二次调用使用 game.scored 中的球员。
const printGoals = function (...players) {
  console.log(`${players.length} goals were scored`);
};
printGoals('Davies', 'Muller', 'Lewandowski', 'Kimmich');
console.log(...game.scored); //将数组逐个展开
printGoals(...game.scored);
// 7. 赔率越低的球队越可能获胜。
//    **不使用 if/else 或三目运算符**,在控制台打印哪支球队更可能获胜。
team1 < team2 && console.log('Team1 is more likely to win');
team1 > team2 && console.log('Team2 is more likely to win');
//左侧为真,&& 必须继续计算右侧表达式
// 右侧是 console.log(...),执行后返回 undefined,但副作用已经在控制台输出了文字。
  • 数组解构
    const [players1, players2] = game.players

  • 对象解构
    const { team1, x: draw, team2 } = game.odds

  • 剩余参数(rest)
    const [gk, ...fieldPlayers] = players1

  • 扩展运算符(spread)
    [...players1, ...players2]printGoals(...game.scored)

  • 模板字符串
    `${players.length} goals were scored`

  • 短路逻辑运算符
    team1 < team2 && console.log(...) 代替 if/else

  • 函数默认参数/可变参数
    function (...players) 接收任意个参数

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐