JS : Array Destructuring
原本寫法:const profile = ["Oluwatobi", "Sofela", "google.com"];
const firstName = profile;
const lastName = profile;
const website = profile;
console.log(firstName); // "Oluwatobi"
console.log(lastName); // "Sofela"
console.log(website); // "google.com"可以寫成:
const profile = ["Oluwatobi", "Sofela", "google.com"];
const = profile;
console.log(firstName); // "Oluwatobi"
console.log(lastName); // "Sofela"
console.log(website); // "google.com"
Direct Array Destructuring
const = [
"Oluwatobi",
"Sofela",
"google.com"
];
console.log(firstName); // "Oluwatobi"
console.log(lastName); // "Sofela"
console.log(website); // "google.com"
也可以:
let firstName, lastName, website;
= ["Oluwatobi", "Sofela", "google.com"];
console.log(firstName); // "Oluwatobi"
console.log(lastName); // "Sofela"
console.log(website); // "google.com"
How to Use Array Destructuring to Assign the Rest of an Array Literal to a Variable
const = ["Oluwatobi", "Sofela", "google.com"];
console.log(firstName); // "Oluwatobi"
console.log(otherInfo); // ["Sofela", "google.com"]
How to Use Array Destructuring to Extract Values at Any Index
const [, , website] = ["Oluwatobi", "Sofela", "google.com"];
console.log(website); // "google.com"
How Default Values Work in an Array Destructuring Assignment
const = ["Oluwatobi"];
console.log(firstName); // "Oluwatobi"
console.log(website); // "Google"
Swap 互換
let firstName = "Oluwatobi";
let website = "Google";
= ;
console.log(firstName); // "Google"
console.log(website); // "Oluwatobi"
How to Use Array Destructuring to Extract Values from an Array to a Function’s Parameters
// Define an array with two items:
const profile = ["Oluwatobi", "Sofela"];
// Define a function with one destructuring array containing two parameters:
function getUserBio() {
return `My name is ${firstName} ${lastName}.`;
}
// Invoke getUserBio while passing the profile array as an argument:
getUserBio(profile);
// The invocation above will return:
"My name is Oluwatobi Sofela."
頁:
[1]