javascript - JS變量被清空
問題描述
代碼中的變量莫名奇妙的被清空,如下圖所示:
代碼如下:
function rolldiceSumProb(arr, sides){ let prob, result=[]; let dig = function(target, count, methods) {if (count > sides) return falseconsole.log(’dig’, target, count)for (let i=1; i<=6; i++) { console.log(’target:’, target, ’count:’, count, ’cur_i:’, i, target+i==arr, sides==count) if (target+i==arr && sides==count) {methods.push(i)result.push(methods)console.log(methods, result, ’quit’)methods.pop()return false } else {methods.push(i)if (target+i < arr) dig(target+i, count+1, methods)methods.pop() }} } dig(0, 1, []) console.log(’res’, result) return prob;}rolldiceSumProb(11, 2)
問題解答
回答1:methods 一直都是用的同一個……雖然它被添加到 result 里了,但是只是添加的引用,并不是復制了一個的, 以你可以添加個復制的結果,比如
result.push([...methods]);
或者用 es5 語法
result.push([].concat(methods));回答2:
你傳入result的是method的引用,如果你清空了method,result自然就沒有值了,你需要把method復制一份傳入result。
相關文章:
1. python - 爬蟲模擬登錄后,爬取csdn后臺文章列表遇到的問題2. 前端 - 誰來解釋下這兩個 CSS selector 區別3. javascript - angular使從elastichearch中取出的文本高亮顯示,如圖所示4. html5 - HTML代碼中的文字亂碼是怎么回事?5. python bottle跑起來以后,定時執行的任務為什么每次都重復(多)執行一次?6. javascript - 求幫助 , ATOM不顯示界面!!!!7. javascript - ios返回不執行js怎么解決?8. 視頻文件不能播放,怎么辦?9. mysql - 分庫分表、分區、讀寫分離 這些都是用在什么場景下 ,會帶來哪些效率或者其他方面的好處10. javascript - vue2如何獲取v-model變量名
