javascript - JS變量被清空
問(wèn)題描述
代碼中的變量莫名奇妙的被清空,如下圖所示:
代碼如下:
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)
問(wèn)題解答
回答1:methods 一直都是用的同一個(gè)……雖然它被添加到 result 里了,但是只是添加的引用,并不是復(fù)制了一個(gè)的, 以你可以添加個(gè)復(fù)制的結(jié)果,比如
result.push([...methods]);
或者用 es5 語(yǔ)法
result.push([].concat(methods));回答2:
你傳入result的是method的引用,如果你清空了method,result自然就沒有值了,你需要把method復(fù)制一份傳入result。
相關(guān)文章:
1. css - 關(guān)于div自適應(yīng)問(wèn)題,大家看圖吧,說(shuō)不清2. docker images顯示的鏡像過(guò)多,狗眼被亮瞎了,怎么辦?3. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””4. docker-machine添加一個(gè)已有的docker主機(jī)問(wèn)題5. mysql - msyql 判斷字段不為空 簡(jiǎn)單方法6. html5 - vue 里的Elemen UI的時(shí)間怎么轉(zhuǎn)化為時(shí)間戳嗎7. angular.js使用$resource服務(wù)把數(shù)據(jù)存入mongodb的問(wèn)題。8. javascript - Vue 自定義控件v-model雙向綁定9. python - django如何每次調(diào)用標(biāo)簽的時(shí)候都取隨機(jī)數(shù)據(jù)10. linux - mysql源碼安裝遇到的問(wèn)題
