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. docker 下面創建的IMAGE 他們的 ID 一樣?這個是怎么回事????2. 運行python程序時出現“應用程序發生異常”的內存錯誤?3. node.js - mongodb查找子對象的名稱為某個值的對象的方法4. html5 - datatables 加載不出來數據。5. javascript - QQ第三方登錄的問題6. 前端 - @media query 使用出現的問題?7. javascript - 在 model里定義的 引用表模型時,model為undefined。8. 利用IPMI遠程安裝centos報錯!9. 測試自動化html元素選擇器元素ID或DataAttribute [關閉]10. html5和Flash對抗是什么情況?

網公網安備