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. javascript - 关于数组的循环遍历问题2. javascript - 正则匹配字符串特定语句后的数字3. 在cmd下进入mysql数据库,可以输入中文,但是查看表信息,不显示中文,是怎么回事,怎新手,请老师4. python - Pycharm调试代码进行列表遍历时,如何直接赋值指定元素5. javascript - 请指条明路,angular的$event,在select中却是undefined?6. java 线程池序号一直增加问题7. docker gitlab 如何git clone?8. java - 重载是不是多态??9. mysql优化 - mysql 多表联合查询,求一个效率最高的查询10. 微信支付 - python做微信企业付款出现CA证书错误

网公网安备