首頁 > web前端 > js教程 > JavaScript:預設參數、擴充運算子、剩餘參數和解構!

JavaScript:預設參數、擴充運算子、剩餘參數和解構!

WBOY
發布: 2024-08-09 09:21:51
原創
335 人瀏覽過

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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板