JavaScript/解构:修订间差异
来自康健生活
小 文字替换 -“{{leftrightflex|”替换为“{{Double-columns|” |
|||
| (未显示同一用户的4个中间版本) | |||
| 第1行: | 第1行: | ||
== 引言 == | == 引言 == | ||
优点是,使用解构,可以减少临时引用的属性。 | |||
eq: | |||
<syntaxhighlight lang="javascript"> | |||
const arr = [1, 2, 3]; | |||
const obj = {foo: 1, bar: 2, biz: 3}; | |||
const [a, b] = arr; | |||
const {foo, bar} = obj;</syntaxhighlight> | |||
== iterable == | |||
== 示例 == | == 示例 == | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
let a = 1; | let a = 1; | ||
let b = 2; | let b = 2; | ||
| 第10行: | 第21行: | ||
2 | 2 | ||
1</pre>}}}} | 1</pre>}}}} | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
const [firstColor = 'white'] = []; | const [firstColor = 'white'] = []; | ||
const [, secondColor = 'black'] = [];</syntaxhighlight>|{{consoleout|<pre> | const [, secondColor = 'black'] = [];</syntaxhighlight>|{{consoleout|<pre> | ||
| 第17行: | 第28行: | ||
</pre>}}}} | </pre>}}}} | ||
{{unknown}} | {{unknown}} | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
const [, ...numbers] = [1, 2, 3];</syntaxhighlight>|{{consoleout|<pre> | const [, ...numbers] = [1, 2, 3];</syntaxhighlight>|{{consoleout|<pre> | ||
(2) [2, 3] | (2) [2, 3] | ||
</pre>}}}} | </pre>}}}} | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
const { foo, ...small } = { | const { foo, ...small } = { | ||
foo: 'value Foo', | foo: 'value Foo', | ||
| 第29行: | 第40行: | ||
"value Foo" | "value Foo" | ||
{bar: "value Bar"} | {bar: "value Bar"} | ||
</pre>}}}} | |||
== 默认值 == | |||
{{Double-columns|<syntaxhighlight | |||
lang="javascript">const aa ={ | |||
a: 1, | |||
b: 2 | |||
} | |||
const {a = 3, d = 4} = aa | |||
console.log('a==>', a); | |||
console.log('d==>', d); | |||
</syntaxhighlight>|{{consoleout|<pre>a==> 1 | |||
d==> 4 | |||
</pre>}}}} | </pre>}}}} | ||