Rest variable là gì?

Noun Javascript
Biến rest

Trong Javascript, biến rest (rest variable) bao gồm toán tử rest (rest operator) và một biến thông thường. Điều này tương tự như với tham số rest (rest parameter), ngoại trừ việc điều này áp dụng cho các danh sách (list) được sử dụng trong một chương trình nói chung và không chỉ giới hạn ở các tham số (parameter).


// Define a destructuring array with two regular variables and one rest variable:
const [name1, name2, ...otherNames] = [
  "Nina", "Sarah", "Steve", "Mike", "Flora"
];

// Print the rest variable items:
console.log(otherNames); 

Trong trường hợp này, toán tử rest (...) hướng dẫn chương trình gán các giá trị còn lại do người dùng cung cấp vào một mảng có tên otherName. Do đó, otherNames là một biến rest (rest variable).

Điều này cũng có thể được áp dụng cho array destructuring.


// Define a destructuring object with two regular variables and one rest variable:
const { name1, name2, ...otherNames } = {
  name1: "Nina",
  name2: "Sarah", 
  name3: "Steve",
  name4: "Mike",
  name5: "Flora"
}

// Invoke the otherNames variable:
console.log(otherNames);

// The invocation above will return:
// {name3: "Steve", name4: "Mike", name5: "Flora"}

Learning English Everyday