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. php - 微信开发验证服务器有效性2. java导入问题3. javascript - Ajax返回json格式之后的数据解析后取出来的数据为undefined?4. javascript - npm安装报错 系统w7 求大神解答5. javascript - vue.js 在使用期间遇到ios9.3.2不兼容问题6. css - 文字排版问题,内容都是动态抓出来的,字数不一定。如何对齐啊7. css3 - 微信前端页面遇到的transition过渡动画的bug8. 网页爬虫 - 关于Python的编码与解码问题9. 前端 - WebStrom安装了angularjs插件,但是没有语法提示10. 正则表达式 - Java:字符串替换带序号

网公网安备