這是我前端一位同事愛用的寫法,雖然很早就知道javascript的object可以解構,但看到這麼多花括號還是會暈,所以決定解析一下她的解構,用法大致上長這樣:
利用Quokka執行的結果,newIndex
的結果分別為1, 2, 1, 2。
{index, aFunction, bFunction} = {index: -1}
可以寫成 {index: index, aFunction: aFunction, bFunction: bFunction} = {index: -1}
,以上面的情況來說,aFunction
, bFunction
皆為空值,而index
為-1
。
解構
解構賦值的說明如下:
The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.
Array
或Object
都可以解構,段落提到的mirror
很傳神的說明了解構的概念。這邊先只討論物件的解構
上面的範例參考這篇文章,這篇講解了使用 {a = <default>, b = <default>}
、{a, b} = {a: <default>, b: <default>}
、{a = <default>, b = <default>} = {}
三個使用效果,正好耦合那位同事的用法。