
大家好,這裡有一些解構類型的例子和簡單練習,希望對你有幫助
嵌套解構:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | const person = {
name: 'John' ,
address: {
city: 'New York' ,
country: 'USA'
}
};
let {
name,
address: { city, country }
} = person;
console.log(name, city, country);
|
登入後複製
解構數組(從數組中提取值並將其儲存在變數中):
1 2 3 | const number = [1,2,3];
let [a,b,c] = number;
console.log(a,b,c);
|
登入後複製
練習:建立一個函數,接收 dd/mm/yyyy 格式的日期並傳回具有單獨值的陣列。使用 split 函數將字串分割成陣列:
1 2 3 | let date = "11/05/2005" ;
let separar = date .split( "/" );
console.log(separar);
|
登入後複製
建立一個函數,接收格式為 dd/mm/yyyy 的日期並傳回具有單獨值的陣列:
1 2 3 4 5 6 7 | let date = "11/05/2005" ;
function splitDate( date ) {
return date .split( '/' );
}
console.log(splitDate( date ));
|
登入後複製
另一種方式:
1 2 3 4 5 6 7 8 | function splitDate(dateString) {
return dateString.split( '/' );
}
let [day, month, year] = splitDate( '20/05/2024' );
console.log(day, month, year);
|
登入後複製
函數參數解構:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | function printPerson1({ name, age, city }) {
console.log(name, age, city);
}
const person = {
name: 'John' ,
age: 30,
city: 'New York'
};
printPerson1(person);
|
登入後複製
同樣的事情,但不同的做法:
1 2 3 4 5 6 7 8 9 | function printPerson2({ name: n, age: a, city: c }) {
console.log(n, a, c);
}
const person = {
name: 'John' ,
age: 30,
city: 'New York'
};
printPerson2(person);
|
登入後複製
這是數組解構而不是物件:
1 2 3 4 5 | function printPerson3([ name, age, city ]) {
console.log(name, age, city);
}
const person = [ 'Jooaca' ,30, 'New York' ];
printPerson3(person);
|
登入後複製
以上是JavaScript 中的解構的詳細內容。更多資訊請關注PHP中文網其他相關文章!