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. 前端 - flex布局采用space-around这种方法,但是最后一行如何让他左对齐?2. php - Redis监控工具,大家有推荐的吗?3. node.js - node的npm无法安装4. chrome - linux系统下如何通过java获取客户端ip和mac地址?5. javascript - sublime已经安装了babel插件和sublimelinter-jshint为什么还是显示es6语法错误?6. 小白问题getDay()7. css - 手机app中rem的基准值计算错误8. 前端 - 使用两个transtion只有一个生效?9. node.js - 服务器上安装了cnpm后,sync不到npm上的代码10. java - git项目迁移到SVN怎么实现的?哪位大神指点指点

网公网安备