展開運算子 ... - daniel-qa/Vue GitHub Wiki
展開運算子 ...
ids: quotaServiceItem.ids ? [...quotaServiceItem.ids] : [],
拆解說明
- 1 . 條件判斷
quotaServiceItem.ids ? ... : []
如果 quotaServiceItem.ids 有值(不是 null、undefined、false),就用它來處理;
否則給一個 空陣列 []。
- 2 . [...quotaServiceItem.ids] 的意思
... 是展開運算子,用來「攤開」陣列元素。
[...quotaServiceItem.ids] 的效果就是「建立一個新陣列,內容跟 quotaServiceItem.ids 一樣」。
這樣可以避免直接引用同一個陣列,產生 修改時會互相影響 的問題。
👉 也就是做了 淺拷貝 (shallow copy)。
舉例
const a = [1, 2, 3];
const b = [...a]; // b = [1, 2, 3]
b.push(4);
console.log(a); // [1, 2, 3] (a 不受影響)
console.log(b); // [1, 2, 3, 4]
如果沒有 ...,而是這樣:
const b = a;
b.push(4);
console.log(a); // [1, 2, 3, 4] (a 也被改掉了!)
- 總結
... 展開運算子:把陣列或物件的元素攤開。
這裡的用法:[...quotaServiceItem.ids] 是在複製一份新的陣列,避免直接引用原始的 quotaServiceItem.ids。
整行意思:
如果 quotaServiceItem.ids 有值,就複製一份新的陣列;沒有的話就給一個空陣列。