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. java - 请教一个IO的问题2. javascript - 自己开发jQuery插件能不能实现一个插件里有多个功能3. h-ui模板导入报错,怎么回事呢,我是用的TP5.14. javascript - 事件的定义有无函数的区别5. 极光推送 - Android app消息推送 百度 极光 个推 信鸽哪个好一些?6. nginx英文文档的WebSocket proxying部分没看太明白,麻烦推荐一点中文文章7. javascript - vue报错,昨天也是这么写的也没报错呀,今天就报错了,不知原因。求解决8. javascript - npm安装报错 系统w7 求大神解答9. PHP类属性声明?10. PHP怎么升级?升级会导致老的网站程序不能用吗?

网公网安备