Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

javascript - What is destructuring assignment and its uses?

I have been reading about Destructuring assignment introduced in ES6.

What is the purpose of this syntax, why was it introduced, and what are some examples of how it might be used in practice?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What is destructuring assignment ?

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

- MDN

Advantages

A. Makes code concise and more readable.

B. We can easily avoid repeated destructing expression.

Some use cases

1. To get values in variable from Objects,array

let obj = { 'a': 1,'b': {'b1': '1.1'}}
let {a,b,b:{b1}} = obj
console.log('a--> ' + a, '
b--> ', b, '
b1---> ', b1)

let obj2 = { foo: 'foo' };
let { foo: newVarName } = obj2;
console.log(newVarName);

let arr = [1, 2, 3, 4, 5]
let [first, second, ...rest] = arr
console.log(first, '
', second, '
', rest)


// Nested extraction is possible too:
let obj3 = { foo: { bar: 'bar' } };
let { foo: { bar } } = obj3;
console.log(bar);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...