01 Atribuição Via Desestruturação (Destructuring Assignment) - JavaScript - MDN
01 Atribuição Via Desestruturação (Destructuring Assignment) - JavaScript - MDN
This page was translated from English by the community. Learn more and join the MDN Web Docs community.
Sintaxe
JS
var a, b, rest;
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
({ a, b } = { a: 1, b: 2 });
console.log(a); // 1
console.log(b); // 2
Descrição
As expressões de objeto e matriz literais fornecem uma maneira fácil de criar pacotes ad hoc de dados .
JS
A atribuição via desestruturação usa sintaxe similar, mas no lado esquerdo da atribuição são definidos quais elementos devem ser
extraídos da variável de origem.
JS
Esse recurso é semelhante aos recursos presentes em linguagens como Perl e Python.
Desestruturação de array
Atribuição básica de variável
JS
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment 1/7
18/03/2024, 21:46 Atribuição via desestruturação (destructuring assignment) - JavaScript | MDN
var [one, two, three] = foo;
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"
var a, b;
Valores padrão
Uma variável pode ser atribuída de um padrão, no caso em que o valor retirado do array é undefined.
JS
var a, b;
[a = 5, b = 7] = [1];
console.log(a); // 1
console.log(b); // 7
Trocando variáveis
Os valores de duas variáveis podem ser trocados em uma expressão de desestruturação.
Sem atribuição via desestruturação, trocar dois valores requer uma variável temporária (ou, em algumas linguagens de baixo nível, o
Algoritmo XOR Swap ).
JS
var a = 1;
var b = 3;
function f() {
return [1, 2];
}
var a, b;
[a, b] = f();
console.log(a); // 1
console.log(b); // 2
Você pode ignorar valores retornados que você não tem interesse:
JS
function f() {
return [1, 2, 3];
}
[, ,] = f();
console.log(protocol); // "https"
Desestruturação de objeto
Atribuição básica
JS
console.log(p); // 42
console.log(q); // true
var a, b;
({ a, b } = { a: 1, b: 2 });
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment 3/7
18/03/2024, 21:46 Atribuição via desestruturação (destructuring assignment) - JavaScript | MDN
Nota: Os parênteses ( ... ) ao redor da declaração de atribuição é uma sintaxe necessária quando se utiliza a atribuição via
desestruturação de objeto literal sem uma declaração.
{a, b} = {a:1, b:2} não é uma sintaxe stand-alone válida, pois {a, b} no lado esquerdo é considarada um bloco, não um objeto
literal.
No entanto, ({a, b} = {a:1, b:2}) é valida, assim como var {a, b} = {a:1, b:2}
console.log(foo); // 42
console.log(bar); // true
Valores padrão
Uma variável pode ser atribuída de um padrão, no caso em que o valor retirado do objeto é undefined.
JS
var { a = 10, b = 5 } = { a: 3 };
console.log(a); // 3
console.log(b); // 5
function drawES5Chart(options) {
options = options === undefined ? {} : options;
var size = options.size === undefined ? "big" : options.size;
var cords = options.cords === undefined ? { x: 0, y: 0 } : options.cords;
var radius = options.radius === undefined ? 25 : options.radius;
console.log(size, cords, radius);
// now finally do some chart drawing
}
drawES5Chart({
cords: { x: 18, y: 30 },
radius: 30,
});
Versão ES2015
JS
function drawES2015Chart({
size = "big",
cords = { x: 0, y: 0 },
radius = 25,
} = {}) {
console.log(size, cords, radius);
// do some chart drawing
}
drawES2015Chart({
cords: { x: 18, y: 30 },
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment 4/7
18/03/2024, 21:46 Atribuição via desestruturação (destructuring assignment) - JavaScript | MDN
radius: 30,
});
var metadata = {
title: "Scratchpad",
translations: [
{
locale: "de",
localization_tags: [],
last_edit: "2014-04-14T08:43:37",
url: "/de/docs/Tools/Scratchpad",
title: "JavaScript-Umgebung",
},
],
url: "/pt-BR/docs/Tools/Scratchpad",
};
var {
title: englishTitle,
translations: [{ title: localeTitle }],
} = metadata;
console.log(englishTitle); // "Scratchpad"
console.log(localeTitle); // "JavaScript-Umgebung"
var people = [
{
name: "Mike Smith",
family: {
mother: "Jane Smith",
father: "Harry Smith",
sister: "Samantha Smith",
},
age: 35,
},
{
name: "Tom Jones",
family: {
mother: "Norah Jones",
father: "Richard Jones",
brother: "Howard Jones",
},
age: 25,
},
];
for (var {
name: n,
family: { father: f },
} of people) {
console.log("Name: " + n + ", Father: " + f);
}
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment 5/7
18/03/2024, 21:46 Atribuição via desestruturação (destructuring assignment) - JavaScript | MDN
function userId({ id }) {
return id;
}
var user = {
id: 42,
displayName: "jdoe",
fullName: {
firstName: "John",
lastName: "Doe",
},
};
console.log(foo); // "bar"
Especificações
Specification
ECMAScript Language Specification
# sec-destructuring-assignment
ECMAScript Language Specification
# sec-destructuring-binding-patterns
diordnA arepO
emorhC
xoferiF
arepO
irafaS
egdE
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment 6/7
18/03/2024, 21:46 Atribuição via desestruturação (destructuring assignment) - JavaScript | MDN
diordnA arepO
emorhC
xoferiF
arepO
irafaS
egdE
Computed Chrome 49 Edge 14 Firefox 41 Opera 36 Safari 10 Chrome 49 Firefox for 41 Oper
property Android Android Andro
names
Chrome 49 Edge 16 Firefox 41 Opera 36 Safari 9.1 Chrome 49 Firefox for 41 Oper
Rest in arrays Android Android Andro
Rest in Chrome 60 Edge 79 Firefox 55 Opera 47 Safari 11.1 Chrome 60 Firefox for 55 Oper
objects Android Android Andro
Tip: you can click/tap on a cell for more information.
Full support See implementation notes.
Veja também
Operadores de Atribuição (en-US)
"ES6 in Depth: Destructuring" on hacks.mozilla.org (em inglês)
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment 7/7