The variables in the code were cleared inexplicably, as shown in the figure below:
code show as below:
function rolldiceSumProb(arr, sides){
let prob, result=[];
let dig = function(target, count, methods) {
if (count > sides) return false
console.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)
phpcn_u15822017-06-07 09:26:10
methods
has always been the same one... Although it has been added to result
, it is only an added reference, not a copy. So you can add a copied result, such as
result.push([...methods]);
Or use es5 syntax
result.push([].concat(methods));
某草草2017-06-07 09:26:10
What you pass into the result is a reference to the method. If you clear the method, the result will naturally have no value. You need to copy the method and pass it into the result.