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. golang - 用IDE看docker源码时的小问题2. javascript - Chrome 扩展,更新别人的扩展 能不能上传到插件商店?3. 这是什么情况???4. android - 哪位大神知道java后台的api接口的对象传到前端后输入日期报错,是什么情况?求大神指点5. 求救一下,用新版的phpstudy,数据库过段时间会消失是什么情况?6. ,我写的代码哪里出错了?为什么就是显示不出来peter?7. Mysql update 分组递增 sql咨询8. html - 爬虫时出现“DNS lookup failed”,打开网页却没问题,这是什么情况?9. nginx和web服务都跑在docker容器里时,nginx负载均衡如何配置服务的IP地址10. mysql sum去除重复

网公网安备