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

Categories

I came across this in some example code and I am completely lost.

const addCounter = (list) => {
    return [...list, 0];  // This is the bit I am lost on, and I don't know about [...list, 0]
}

Apparently the above is equal to the following:

const addCounter = (list) => {
    return list.concat([0]);
}

Any suggestion or explaination is much appreciated.

Question&Answers:os

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

1 Answer

...list is using the spread syntax to spread the elements of list. Let's assume the list is [1, 2, 3]. Therefore [...list, 0] becomes:

[1, 2, 3, 0]

Which has the same result as doing list.concat([0]);

This is not a feature of the array in ES6, it's just been used for array concatenation. It has other uses. Read more on MDN, or see this question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...