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. node.js - mysql如何通过knex查询今天和七天内的汇总数据2. mysql 插入数值到特定的列一直失败3. 360浏览器与IE浏览器有何区别???4. mysql - 百万行的表中是否尽量避免使用update等sql语句?5. python - 在使用Pycharm时经常看到如下的样式,小括号里红色的部分是什么意思呢?6. Python从URL中提取域名7. javascript - 新浪微博网页版的字数限制是怎么做的8. 怎么在网页中设置图片进行左右滑动9. javascript - 豆瓣的这个自适应是怎么做的?10. javascript - 用jsonp抓取qq音乐总是说回调函数没有定义
