简体   繁体   中英

SPREAD operator in array destructuring

In the below example, unmapped array items must be mapped to rest parameter in the left hand side, but for some reason the output is different,

var planets = ["Mercury", "Earth", "Venus", "Mars", "Pluto", "Saturn"];
var [first, second, ...rest] = ["Mercury", "Earth", ...planets, "Saturn"];

console.log(first); //Output: Mercury
console.log(second); //Output: Earth

Now for the below, expected output is,

console.log(rest); //Output: ["Venus", "Mars", "Pluto", "Saturn"]

But the actual output is,

console.log(rest); //Output: "Mercury", "Earth", "Venus", "Mars", "Pluto", "Saturn", "Saturn"

Source: https://www.freecodecamp.org/news/array-destructuring-in-es6-30e398f21d10/

Whats happening here?

When you spread planet into your your second array, you're putting all the elemtns from the planets array into the second array, so:

["Mercury", "Earth", ...planets, "Saturn"];

... evaluates to:

["Mercury", "Earth", "Mercury", "Earth", "Venus", "Mars", "Pluto", "Saturn", "Saturn"];

you then destructure the first and second elements from this array giving you "Mercury" and "Earth" . You then use the rest pattern ...rest to retrieve the remaining elements (ie elements from index 2 and onwards) and store them in the array named rest . Thus, your rest array contains all the elements from the array above, excluding the first and second elements:

["Mercury", "Earth", "Venus", "Mars", "Pluto", "Saturn", "Saturn"]

To do get your expected output, you can destucture the first array, by ignoring the first two elements:

 const [,,...rest] = ["Mercury", "Earth", "Venus", "Mars", "Pluto", "Saturn"]; console.log(rest);

You can use Set()

The Set object lets you store unique values

 var planets = ["Mercury", "Earth", "Venus", "Mars", "Pluto", "Saturn"]; var [first, second, ...rest] = new Set(["Mercury", "Earth", ...planets, "Saturn"]); console.log(first); console.log(second); console.log(rest);

You can spread selectively. When you spread ...planets it copies all the values from planets array to the array you're creating.

You can simply use slice before spreading.

 var planets = ["Mercury", "Earth", "Venus", "Mars", "Pluto", "Saturn"]; var [first, second, ...rest] = ["Mercury", "Earth", ...planets.slice(2, planets.length - 1), "Saturn"]; console.log(first); console.log(second); console.log(rest)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM