這是來自nodechool的功能性JavaScript研討會。這裏是代碼,因爲它出現在那裏:這個遞歸函數是如何結束的?
function toUpperArray(items) {
if (!items.length) return [] // end condition
var head = items[0] // item to operate
head = head.toUpperCase() // perform action
var tail = items.slice(1) // next
return [head].concat(toUpperArray(tail)) // recursive step
}
toUpperArray(['hello', 'world']) // => ['HELLO', 'WORLD']
我不明白「最終條件」如何工作。我認爲條件是尋找items.length爲0,但它然後返回一個空數組?我試圖通過讓它不返回任何東西來運行它,這會返回undefined,從而將未定義的數組添加到最終數組中,但我不確定爲什麼返回一個空數組修復了這個問題。我期望最後一個數組中的最後一個項目是一個空數組。
而且,我從來沒有見過一個條件未使用大括號。這很重要嗎?
因爲'[head] .concat([])'會返回'[head]'。 –
另外'{}'是隻有一個語句的情況下可選的。 –
在MDN上閱讀關於「if」的信息以獲取大括號https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/if...else – epascarello