JavaScript 的陣列解構語法,是一種從陣列取出值並將它們指定給不同變數的簡潔方式。
在這個例子中,numberOfMoons陣列裡的每個值都會被指定給對應的行星:
const numberOfMoons = [0, 2, 14];
const [venus, mars, neptune] = numberOfMoons;
neptune;
// => 14
簡而言之:
在 JavaScript 中,也有解構語法可以從物件取出屬性,並將它們指定給不同的變數。
在這個例子中,會從weather物件取出天氣符號:
const weather = {
sun: '☀️',
sun_behind_small_cloud: '🌤️',
sun_behind_cloud: '⛅',
sun_behind_large_cloud: '🌥️',
sun_behind_rain_cloud: '🌦️',
cloud: '☁️',
cloud_with_rain: '🌧️',
cloud_with_snow: '🌨️',
cloud_with_lightning: '🌩️',
cloud_with_lightning_and_rain: '⛈️',
};
const { sun, cloud, cloud_with_lightning: thunder } = weather;
sun;
// => '☀️'
cloud;
// => '☁️'
thunder;
// => '🌩️'
簡而言之:
Elyse 是個準魔術師,持續精進她的訓練。 她有一副想操弄的牌。
為了方便起見,她通常只會用到編號 2 到 10 的牌,不過有些把戲可能會用到額外的人頭牌。
把牌重新排列有很多種方式,但為了維持魔術的假象,絕對不能使用其中任何一種方法,例如 Elyse 不會使用splice、slice、shift、unshift、push、at。
陣列存取子array[index]與物件存取子(object[key]和object.key)也絕對不能使用。
想幫 Elyse 的魔術更上一層樓嗎?
每個函式都可以用參數,以及一個只包含單一 return expression 的函式主體來實作。
Elyse 會在不使用array[index]、.at(index)或.shift()的情況下,召喚出牌組中的第一張牌。
就像變魔術一樣。
const deck = [5, 9, 7, 1, 8];
getFirstCard(deck);
// => 5
Elyse 施展手法,在不使用array[index]或.shift()的情況下,召喚出牌組中的第二張牌。
const deck = [3, 2, 10, 6, 7];
getSecondCard(deck);
// => 2
Elyse 會讓牌組中的兩張牌互換位置。 她完全不需要呼叫任何函式。
const deck = [10, 7];
swapTwoCards(deck);
// => [7, 10]
為了再施展一些手法,Elyse 取出三張牌,迅速把最上面的牌移到最後面,讓中間那張牌變成第一張,原本最下面的牌則變成中間那張。 她完全不需要呼叫任何函式。
const deck = [2, 6, 10];
shiftThreeCardsAround(deck);
// => [6, 10, 2]
Elyse 會把牌組分成兩堆。
接著她請觀眾從兩堆中挑一堆,我們把它命名為chosen。
另一堆disregarded不再重要,於是她讓它消失。
她完全不需要呼叫任何函式。
const deck = [5, 4, 7, 10];
const chosen = [5, 4];
const disregarded = [7, 10];
pickNamedPile({ chosen, disregarded });
// => [5, 4]
可惜觀眾老是挑到「錯」的那一堆,但靠著巧妙又迅速的手法,Elyse 把chosen那一堆改名成disregarded,並把disregarded那一堆改名成chosen。
她完全不需要呼叫任何函式。
const deck = [5, 4, 7, 10];
const chosen = [5, 4];
const disregarded = [7, 10];
swapNamedPile({ chosen, disregarded });
// => { chosen: [7, 10], disregarded: [5, 4] }