admin管理员组文章数量:1432368
I came upon this piece of code let [a,,b] = [1, 2, 3];
javascript at the babel piler website and it has made me curious. What is it doing exactly? How and where can I use it in a useful way?
I came upon this piece of code let [a,,b] = [1, 2, 3];
javascript at the babel piler website and it has made me curious. What is it doing exactly? How and where can I use it in a useful way?
3 Answers
Reset to default 4let [a,,b] = [1, 2, 3]
This is part of something called destructuring assignment.
The double ma denotes that a value (on the right side of the operation) should be skipped.
Ergo, a
will have the value 1 and b
will have 3. Nothing will be assigned the value 2.
It names: Destructuring. It is super useful for handling objects ands arrays.
I will try to give you a real example usage:
Imagine you are working with a form, where you have to pass some fileds of information through it, and save it in your database.
//Form:
Name: Donald
City: USA
Age: 45
You will need to pass this data, in some object called 'formData':
const formData = {name:'donald', city:'USA',age:45}
If you need to handle each object's element, you will have to write everytime:
console.log(formData.name) // => donald
console.log(formData.city) // => USA
console.log(formData.age) // => 45
With destructuring, you can rename this elements in variables:
const {name, city, age} = formData
You are assigning for each formData element a constant variable, easier to write and read it:
console.log(name) // => Donald
console.log(city) // => USA
console.log(age) // => 45
In your case, element between mas, it will be skkiped:
const array = [1,2,3]
const a,,c} = array;
console.log(a) // => 1
// b position will be skipped
console.log(c) // => 3
There is another feature part of destructuring: rest pattern (as @VLAZ said)
const rainbow = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
const [red,, yellow, ...otherColors] = rainbow;
console.log(otherColors); // ['green', 'blue', 'indigo', 'violet']
Check more examples and possible cases:
clickHere
This is a concept known as destructuring, and you can read more about it here. The code you are asking about simply obtains the first and last items of an array, ignoring the one in the middle. It is used when you just don't care about a specific position in an array so you don't bother saving it to a variable (see the Ignoring some returned values section in the link above).
本文标签: javascriptWhat is quotlet ab1234
版权声明:本文标题:javascript - What is "let [a,,b] = [1, 2, 3, 4, 5]" with two commas (,,) doing and how can it be used? - Stack 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745152463a2644981.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论