# 錯誤範例
buggySleepSort = (numbers) ->
for n in numbers
setTimeout(
console.log n
n
)
buggysleepSort [4, 2, 6, 9, 3]
for n in numbers
setTimeout(
console.log n
n
)
buggysleepSort [4, 2, 6, 9, 3]
3 3 3 3 3
而不是4, 2, 6, 9, 3
原因是當setTimeout執行時, n value已被loop到最後一個item (3, call by reference)
# 正確解法
sleepSort = (numbers) ->
for num in numbers
do (num) ->
setTimeout ->
console.log num
sleepSort [4, 2, 6, 3]
若想要避免各語言的pitfall,可參考wiki page,
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
沒有留言:
張貼留言