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. angular.js - 用angular2-cli打包项目之后,跳转路由刷新会报404的错误2. angular.js - angular2动态显示隐藏组件问题3. angular.js - 在用会话存储传递参数时,使用angularjs冲突4. angular.js - 请教angularjs里html和js通信的问题5. jquery - angularjs的数据为什么渲染不到页面上?数据获取到了,我的代码哪里出了错了?6. angular.js - 我想实现打印angular $scope数据,代码如何实现呢?求教(如下图)7. node.js - 怎么在初始化的时候使得一个子组件不加载?8. python - 如何在docker上部署pyspider9. python - Ubuntu16.04LTS登录后只显示屏保10. Python中的内列表问题,真的很困惑