JavaScript/解构:修订间差异
来自康健生活
小 文字替换 -“{{leftrightflex|”替换为“{{Double-columns|” |
|||
| 第12行: | 第12行: | ||
== 示例 == | == 示例 == | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
let a = 1; | let a = 1; | ||
let b = 2; | let b = 2; | ||
| 第21行: | 第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> | ||
| 第28行: | 第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', | ||
| 第43行: | 第43行: | ||
== 默认值 == | == 默认值 == | ||
{{ | {{Double-columns|<syntaxhighlight | ||
lang="javascript">const aa ={ | lang="javascript">const aa ={ | ||
a: 1, | a: 1, | ||
2026年11月26日 (四) 08:31的最新版本
引言
优点是,使用解构,可以减少临时引用的属性。
eq:
const arr = [1, 2, 3];
const obj = {foo: 1, bar: 2, biz: 3};
const [a, b] = arr;
const {foo, bar} = obj;
iterable
示例
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a);
console.log(b);
2 1
const [firstColor = 'white'] = [];
const [, secondColor = 'black'] = [];
white black
(来源摘自互联网示例,作者 未知)
const [, ...numbers] = [1, 2, 3];
(2) [2, 3]
const { foo, ...small } = {
foo: 'value Foo',
bar: 'value Bar'
};
"value Foo"
{bar: "value Bar"}
默认值
const aa ={
a: 1,
b: 2
}
const {a = 3, d = 4} = aa
console.log('a==>', a);
console.log('d==>', d);
a==> 1 d==> 4
No categories