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. html5 - rudy编译sass的时候有中文报错2. javascript - ie11以下单击打开不了file,双击可以。求解?3. javascript - 关于定时器 与 防止连续点击 问题4. css - 前后端交互问题!5. javascript - js 有什么优雅的办法实现在同时打开的两个标签页间相互通信?6. objective-c - ios百度地图定位问题7. javascript - node.js服务端渲染解疑8. javascript - 求助这种功能有什么好点的插件?9. javascript - 求助关于js正则问题10. 微信开放平台 - Android调用微信分享不显示
