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] }