admin 發表於 2021-11-12 23:13:19

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"

admin 發表於 2021-11-12 23:15:36

Direct Array Destructuring
const = [
    "Oluwatobi",
    "Sofela",
    "google.com"
];

console.log(firstName); // "Oluwatobi"
console.log(lastName); // "Sofela"
console.log(website); // "google.com"

admin 發表於 2021-11-12 23:18:02

也可以:
let firstName, lastName, website;

= ["Oluwatobi", "Sofela", "google.com"];

console.log(firstName); // "Oluwatobi"
console.log(lastName); // "Sofela"
console.log(website); // "google.com"

admin 發表於 2021-11-12 23:22:02

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"]

admin 發表於 2021-11-12 23:24:17

How to Use Array Destructuring to Extract Values at Any Index
const [, , website] = ["Oluwatobi", "Sofela", "google.com"];

console.log(website); // "google.com"

admin 發表於 2021-11-12 23:27:19

How Default Values Work in an Array Destructuring Assignment
const = ["Oluwatobi"];

console.log(firstName); // "Oluwatobi"
console.log(website); // "Google"

admin 發表於 2021-11-12 23:29:37

Swap 互換
let firstName = "Oluwatobi";
let website = "Google";

= ;

console.log(firstName); // "Google"
console.log(website); // "Oluwatobi"

admin 發表於 2021-11-12 23:40:30

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]
查看完整版本: JS : Array Destructuring