Ta gán bộ ba biến bằng các phần tử có trong mảng:
const numbers = [1, 2, 3]
let [numOne, numTwo, numThree, numFour] = numbers
console.log(numOne, numTwo, numThree, numFour) // 1 2 3 undefined
Phần tử thứ tư trong mảng không có, nên numFour = undefined
.
Default Values
Có thể dùng giá trị mặc định cho các biến khi sử dụng destructuring. Việc này đảm bảo giá trị của các biến không bị undefined
:
const names = [undefined, "Harry", "Hermione"]
let [
firstPerson = "Voldemort",
secondPerson,
thirdPerson,
fourthPerson = "Ron",
] = names
console.log(firstPerson, secondPerson, thirdPerson, fourthPerson) // Voldemort Harry Hermione Ron
Two-dimension Array
Trích xuất từ mảng hai chiều:
const fullStack = [
["HTML", "CSS", "JS", "React"],
["Node", "Express", "MongoDB"],
]
const [frontEnd, backEnd] = fullStack
console.log(frontEnd) // ['HTML', 'CSS', 'JS', 'React'],
console.log(backEnd) // ['Node', 'Express', 'MongoDB']
Omit an Element
Bỏ qua một phần tử bất kỳ sử dụng dấu phẩy (,
):
const scientificConstants = [2.72, 3.14, 9.81, 37, 100]
let [e, pi, , bodyTemp, boilingTemp] = scientificConstants
console.log(e, pi, bodyTemp, boilingTemp) // 2.72 3.14 37 100
Rest Operator
Tip
Chúng ta có thể không muốn gán hết tất cả các phần tử của mảng cho các biến mà chỉ muốn gán vài phần tử đầu. Khi đó, ta có thể gán các phần tử còn lại bằng cách dùng toán tử rest
...
(Rest Operator).
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let [numOne, numTwo, numThree, ...others] = numbers
console.log(numOne, numTwo, numThree) // 1, 2, 3
console.log(others) // [4, 5, 6, 7, 8, 9, 10]
As Loop Variables
Có thể sử dụng các biến destructuring làm biến của vòng lặp for of
:
const countries = [
["Finland", "Helsinki"],
["Sweden", "Stockholm"],
["Norway", "Oslo"],
]
for (const [country, city] of countries) {
console.log(country, city)
}
/*
"Finland" "Helsinki"
"Sweden" "Stockholm"
"Norway" "Oslo"`
*/
Related
table tags as Tags, file.cday as Created
from [[Array Destructuring]]
sort file.ctime asc