[英]What is meaning of this three lines in App module.ts Angular file
[英]Angular what's the meaning of these three dots in @NGRX
這三個點到底是什么意思,我為什么需要它們?
export function leadReducer(state: Lead[]= [], action: Action {
switch(action.type){
case ADD_LEAD:
return [...state, action.payload];
case REMOVE_LEAD:
return state.filter(lead => lead.id !== action.payload.id )
}
}
這三個點被稱為來自 Typescript(也來自ES7 )的擴展運算符。
擴展運算符返回數組的所有元素。 就像您將分別編寫每個元素一樣:
let myArr = [1, 2, 3];
return [1, 2, 3];
//is the same as:
return [...myArr];
這主要是語法糖,因為它編譯了這個:
func(...args);
對此:
func.apply(null, args);
在您的情況下,這將被編譯為:
return [...state, action.payload];
//gets compiled to this:
return state.concat([action.payload]);
它是一個擴展運算符 (...),用於擴展數組/對象的元素或用於從另一個數組或對象初始化數組或對象。
讓我們從現有數組創建新數組來理解這一點。
讓 Array1 = [ 1, 2, 3]; //1,2,3
讓 Array2 = [ 4, 5, 6]; //4,5,6
//從現有數組創建新數組
讓 copyArray = [...Array1]; //1,2,3
//通過合並兩個數組創建數組
讓 mergeArray = [...Array1, ...Array2]; //1,2,3,4,5,6
//從現有數組+更多元素創建新數組
讓 newArray = [...Array1, 7, 8]; //1,2,3,7,8
...
( 擴展運算符)通過將索引0
中的每個值返回到索引length-1
來工作:
上下文:在使用子數組(或任何其他二級屬性)時,請注意三點擴展語法的這種特殊行為(按值/按引用)。
發現:注意嵌套數組(或子屬性)不是通過值傳遞,而是通過引用傳遞。 換句話說,只有第一級項目作為副本“按值”傳遞。 請參閱示例:
sourceArray = [ 1, [2, 3] ] // Second element is a sub-array targetArray = [ ...sourceArray] console.log("Target array result:", JSON.stringify(targetArray), "\n\n") //it seems a copy, but... console.log("Let's update the first source value:\n") sourceArray[0] = 10 console.log("Updated source array:", JSON.stringify(sourceArray), "\n") console.log("Target array is NOT updated, It keeps a copy by value:") console.log(JSON.stringify(targetArray), "\n\n") //But if you update a value of the sub-array, it has NOT been copied console.log("Finally, let's update a nested source value:\n") sourceArray[1][0] = 20 console.log("Updated source nested array:", JSON.stringify(sourceArray), "\n") console.log("Target array is updated BY REFERENCE! ", ) console.log(JSON.stringify(targetArray), "\n\n") // it is not a copy, it is a reference! console.log("CONCLUSION: ... spread syntax make a copy 'by value' for first level elements, but 'by reference' for second level elements (This applies also for objects) so take care!\n")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.