最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is "let [a,,b] = [1, 2, 3, 4, 5]" with two commas (,,) doing and how can it be used? - Stack

programmeradmin2浏览0评论

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?

Share Improve this question edited Dec 29, 2019 at 21:06 Mitya 34.7k13 gold badges68 silver badges124 bronze badges asked Dec 29, 2019 at 20:58 uberuber 5,1136 gold badges32 silver badges65 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 4
let [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).

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论