首页 > web前端 > js教程 > 正文

JavaScript:默认参数、扩展运算符、剩余参数和解构!

WBOY
发布: 2024-08-09 09:21:51
原创
298 人浏览过

JavaScript: Default Parameters, Spread Operator, Rest Parameters, and Destructuring!

默认参数

我们可以直接在参数列表中添加默认值

function rollDie(numSides = 6) {
  return Math.floor(Math.random() * numSides) + 1;
}
登录后复制

在这里,我们需要注意秩序。默认参数只能出现在任何没有默认值的参数之后:

function greet(person, msg = 'Hey there', punc = '!') {
  return `${msgs}, ${person}${punc}`;
}
登录后复制

传播

Spread 语法允许迭代,例如在需要零个或多个参数(对于函数调用)或元素(对于数组文字)的地方扩展数组,或者在零个或多个参数的地方扩展对象表达式预计会有更多键值对(用于对象文字)。 -MDN

我们可以在数组上使用展开运算符:

console.log(Math.max(1, 2, 3, 4, 5, 2)); // 5
const nums = [4, 3, 53, 3, 5, 2, 4, 920, 3, 5, 2];
console.log(Math.max(...nums)); // 920
登录后复制

我们可以使用扩展运算符来连接数组:

const cats = ['Fluffy', 'Zane', 'Jim'];
const dogs = ['Doggo', 'Sir Barks A Lot'];
const allPets = [...cats, ...dogs, 'Goldy'];
console.log(allPets); //['Fluffy', 'Zane', 'Jim', 'Doggo', 'Sir Barks A Lot', 'Goldy']
登录后复制

我们可以使用 spread 将属性从一个对象复制到另一个对象:

const feline = {
  legs: 4,
  family: 'Felidae',
};
const canine = {
  family: 'Canine',
  furry: true,
};

const dog = { ...canine, isPet: true };
console.log(dog); // {family: 'Canine', furry: true, isPet: true}

// Note, order matters - the last property takes precidence:
const catDog = { ...feline, ...canine };
console.log(catDog); // {legs: 4, family: 'Canine', furry: true}
登录后复制

在数组和字符串上传播使用索引作为键值:

let newObj = { ...[2, 4, 6, 8] };
console.log(newObj); // {0: 2, 1: 4, 2: 6, 3: 8}

let anotherObj = { ...'Hello' };
console.log(anotherObj); //{0: 'H', 1: 'e', 2: 'l', 3: 'l', 4: 'o'}
登录后复制

使用传播的一个更现实的例子是,如果我们想将数据添加到表单中:

const dataFromForm = {
  email: 'jim@jimelm.com',
  password: '1234',
  username: 'jimelm',
};

const person = { ...dataFromForm, id: 2134, isAdmin: false };
console.log(person); // {email: 'jim@jimelm.com', password: '1234', username: 'jimelm', id: 2134, isAdmin: false}
登录后复制

其余参数

休息与传播相反。它将一堆参数传递给函数并将它们组合成一个数组。一些例子包括:

function sum(...nums) {
  return nums.reduce((total, el) => total + el);
}

function raceResults(gold, silver, ...everyoneElse) {
  console.log(`Gold metal goes to ${gold}`);
  console.log(`Silver metal goes to ${silver}`);
  console.log(`And thanks to: ${everyoneElse}`);
}
登录后复制

解构

解构数组

这是解构数组的示例:

const scores = [999, 888, 777, 666, 555, 444];

const [gold, silver, bronze, ...otherScores] = scores;
console.log(gold); // 999
console.log(silver); // 888
console.log(bronze); // 777
console.log(otherScores); // [666, 555, 444]
登录后复制

解构对象

这里我们将解构一个对象:

const user = {
  email: 'marryelm@what.com',
  password: '134jsdf',
  firstName: 'Marry',
  lastName: 'Elm',
  born: 1927,
  died: 2091,
  city: 'Hayward',
  state: 'CA',
};

const { email, state, city } = user;
console.log(email); // marryelm@what.com
console.log(state); // CA
console.log(city); // Hayward

const { born: birthYear } = user;
console.log(birthYear); // 1927
登录后复制

我们可以为变量指定默认值,如下所示:

const user2 = {
  email: 'stacy@what.com',
  firstName: 'stacy',
  lastName: 'kent',
  born: 1984,
  city: 'Boise',
  state: 'ID',
};

const { city, state, died } = user2;
console.log(died); // undefined

const { city, state, died = 'N/A' } = user2;
console.log(died); // N/A
登录后复制

解构参数

我们还可以在函数参数内解构:

const user2 = {
  email: 'stacy@what.com',
  firstName: 'stacy',
  lastName: 'kent',
  born: 1984,
  city: 'Boise',
  state: 'ID',
};

function fullName({ firstName, lastName = '???' }) {
  return `${firstName} ${lastName}`;
}
登录后复制

我们还在回调函数中进行解构:

const movies = [
  {
    title: 'Indiana Jones',
    score: 77,
    year: 1994,
  },
  {
    title: 'Star Trek',
    score: 94,
    year: 1983,
  },
  {
    title: 'Deadpool',
    score: 79,
    year: 2001,
  },
];

let ratings = movies.map(({ title, score }) => {
  return `${title} is rated ${score}`;
});

console.log(ratings); // ['Indiana Jones is rated 77', 'Star Trek is rated 94', 'Deadpool is rated 79']
登录后复制

以上是JavaScript:默认参数、扩展运算符、剩余参数和解构!的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!