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 計算兩個時間相差的分鐘數,超過一天時計算不對2. javascript - 使用form進行頁面跳轉,但是很慢,如何加一個Loading?3. angular.js - angularjs 注入模塊報錯 很怪異... 求解惑4. angular.js - 輸入郵箱地址之后, 如何使其自動在末尾添加分號?5. javascript - JS 里面的 delete object.key 到底刪除了什么?6. javascript - ES6規范下 repeat 函數報錯 Invalid count value7. javascript - html5的data屬性怎么指定一個function函數呢?8. html5 - 為什么使使用vue cli 腳手架,post-css 沒有自動對css3屬性自動添加瀏覽器前綴呢?9. java如何生成token?10. javascript - 后臺管理系統左側折疊導航欄數據較多,怎么樣直接通過搜索去定位到具體某一個菜單項位置,并展開當前菜單
