Home >Web Front-end >JS Tutorial >JavaScript Array Destructuring
->in this post you will learn to destruct arrays, Skipping a value in the array, and Switching variables
Destructuring Arrays
We use destructuring to retrieve elements from the array and store them into variables.
Array Destructuring assignment = []
Example:
const arr = ['rice', 'pizza', 'chicken']; // without Destructuring: const foodOne = arr[0]; const foodTwo = arr[1]; const foodThree = arr[2]; console.log(foodOne, foodTwo, foodThree); // rice pizza chicken // with Destructuring const [food1, food2, food3] = arr; console.log(food1, food2, food3); // rice pizza chicken
Note: Destructuring Doesn't destroy the original array, we just UNPACK it, for illustration:
console.log(arr); // rice pizza chicken
Skipping a value:
let [food1, , food3] = arr; console.log(food1, food3); // rice chicken
Switching variables:
if we wanted the first food to be chicken instead of rice, and the third one rice instead of chicken, we can switch their places and their values will be switched, example:
[food1, food3] = [food3, food1]; console.log(food1, food3); // chicken rice
I hope this helped you get a better understanding of JavaScript array destructuring. Feel free to ask any questions in the comments below :)
The above is the detailed content of JavaScript Array Destructuring. For more information, please follow other related articles on the PHP Chinese website!