为了理解在ES6中引入的 更新的破坏语法,让我们覆盖旧
的方式. 我将在整个过程中提到这一点几次,但这些是可帮助的可选语法。
1// some object
2const apple = {
3 numberOfLeaves: 2,
4 colors: {
5 actual: ['green', 'yellow'],
6 possible: ['red', 'green', 'yellow'],
7 },
8 kind: 'Golden Delicious',
9 sku: 'A-GD-01',
10};
以下是我们如何从 ES6 之前的对象中获取值:
1// property accessors using the dot syntax
2const kind = apple.kind;
3const sku = apple.sku;
现在我们有破坏,我们可以这样做,从对象中提取这两个属性,并将它们分配给新的const
变量:
1const { kind, sku } = apple;
它方便地访问嵌入值,您也可以为变量选择自己的名称 - 它不必匹配属性名称!
1// instead of:
2// const colors = apple.colors.actual;
3// const possibleColors = apple.colors.possible;
4
5const { actual: colors, possible: possibleColors } = apple.colors;
6
7console.log(colors); // outputs ["green", "yellow"]
8console.log(possibleColors); // outputs ["red", "green", "yellow"]
雷达破坏
数组破坏是非常相似的,它允许我们从数组中仅获取某些值,例如:
1const names = ['Jack', 'Janet', 'John', 'Jessie', 'Jaqueline', 'Jerry', 'Justin', 'Julie', 'Jake'];
2
3const [first, second, third, ...theRest] = names;
4
5console.log(first); // outputs "Jack"
6
7console.log(theRest); // outputs ["Jessie", "Jaqueline", "Jerry", "Justin", "Julie", "Jake"]
正如你所看到的,我们将前3个元素提取到自己的变量中,并使用 rest 语法 ...
将剩余值分配到另一个新的变量中。
我们不必将剩余的值分配给变量,假设我们只想要第一个数组值 - 我们只能将变量嵌入组合中。
现在,我们将将数组破坏与对象破坏相结合,以提取我们想要的一个值,将提取减少为一个陈述。
1const winners = [
2 { name: 'Mario', time: 110 },
3 { name: 'Waluigi', time: 115 },
4 { name: 'Toad', time: 116 },
5 { name: 'Yoshi', time: 124 },
6 { name: 'Bowser', time: 129 },
7];
8
9function getBestTimeOf(racers) {
10 // extract only the first item and from that, we only assign
11 // the property of time to the new variable of bestTime
12 const [{ time: bestTime }] = racers;
13 return bestTime;
14}
15
16console.log( getBestTimeOf(winners) ); // outputs 110
有些人可能不认为这种提取比const bestTime = winners[0].time;
更干净,我同意我们可能会失去一些快速阅读代码的能力,这就是为什么每个策略在实施之前都需要预见和常识。
两个更快的线索为 arrys
您可以交换值,假设它们不是用const
定义的
1let a = 2;
2let b = 5;
3
4[a, b] = [b, a];
5console.log(a); // 5
6console.log(b); // 2
- 您可以跳过值,将插槽留下一个字符串. 在本示例中,我只会抽出第二个值. 不要担心正常的表达式使用 - 我从我的项目中稍微改变了代码以显示可能的使用
1const [,, three] = [1, 2, 3, 4, 5, 6, 7];
2console.log(`I selected ${three}.`); // outputs "I selected 3."
多重返回值
您可以使用数组破坏来清晰地返回函数中的多个值! 使用 新连接功能的 React 开发人员可能熟悉该函数的使用方式:
1const [count, setCount] = useState(0);
要获得返回多个值的相同功能,您只需要返回这些值。
1function getCoordinates(address) {
2 // use an API to get the lon/lat of an address
3 const coordinates = maps.address(address).coordinates;
4 return [coordinates.lon, coordinates.lat];
5}
6
7// later I can get this with
8const [longitude, latitude] = getCoordinates(someAddress);
表达式参数 / 参数语法
这是我最喜欢的破坏使用方式,我们将将对象作为我们的函数参数和论点使用!这可以大大简化函数的结构。
<$>[注] 要澄清 — 参数是函数声明中的变量. 参数是您在调用函数参数时传输的数据。
下面是澄清这些定义的片段,不要太注意代码正在做什么 - 看看笔记是指什么。
1// level and data are the parameters
2function logData(level, data) {
3 console.log(`New log of level: ${level}`);
4 console.log(data);
5}
6
7const someLevel = 'error';
8const calculatedData = {
9 id: 1,
10 name: 'Jack',
11};
12
13// the VALUES of someLevel and calculatedData are the arguments
14// we are passing to logData() - the variable names are irrelevant
15logData(someLevel, calculatedData);
这里有一些可以控制电信交换机的一部分的代码. 这个函数在通话渠道上设置了变量. 再次,忽略实际的代码目的,并专注于笔记和策略。
1// ...inside a class
2async set({
3 variable = '',
4 value = '',
5 callId = '',
6} = {})
7{
8 console.log(`Setting ${variable} equal to ${value} on call ID: ${callId}`);
9 return await this.api('call_setvar', `${callId} ${variable} ${value}`);
10}
我将这个函数称为:
1// callId and url are defined above
2
3await this.set({ callId, variable: 'custom_transfer_url', value: url });
通过一个对象并在另一端被暗示破坏的这种方法给了我们一些宝贵的益处:
- 命名参数(自我文档)
- 默认值(通过
=
符号) ** - 顺序不相应
- 对象 属性值简称 (使用相同的名称为持有值的属性和变量,例如如何传输 uuid)
uuid: uuid,
缩短为uuid,
您不必将每个变量放在不同的行上,正如您在我的函数声明中所看到的。
<$>[注] ** 请注意,默认值只有当值未定义时才会使用,这意味着它没有被传入或明确设置为未定义。
我希望这些使用的数组和对象破坏给了你一些新的方式来简化和结构你的代码! 如果你认为你的同事开发人员可以使用这些提示,请与他们分享。