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 里了,但是只是添加的引用,并不是復(fù)制了一個的, 以你可以添加個復(fù)制的結(jié)果,比如
result.push([...methods]);
或者用 es5 語法
result.push([].concat(methods));回答2:
你傳入result的是method的引用,如果你清空了method,result自然就沒有值了,你需要把method復(fù)制一份傳入result。
相關(guān)文章:
1. docker 下面創(chuàng)建的IMAGE 他們的 ID 一樣?這個是怎么回事????2. 在應(yīng)用配置文件 app.php 中找不到’route_check_cache’配置項3. html按鍵開關(guān)如何提交我想需要的值到數(shù)據(jù)庫4. objective-c - 自定義導(dǎo)航條為類似美團的搜索欄樣式5. ios - vue-cli開發(fā)項目webstrom會在stylus樣式報錯,飆紅,請大神幫忙6. html5 - 用Egret寫的小游戲,怎么分享到微信呢?7. css - BEM 中塊(Block)有木有什么標準 何時決定一個部分提取為塊而不是其父級的元素呢(Element)?~8. css3 - 怎么感覺用 rem 開發(fā)的不多啊9. css - width設(shè)置為100%之后列表無法居中10. python - 在pyqt中做微信的機器人,要在表格中顯示微信好友的名字,卻顯示不出來,怎么解決?
