写js时出现一个问题,想不通为什么,求大神解释
function maxSubSum(arr,left,right){
//console.log(right);
var leftMaxSum = rightMaxSum = 0;
//将这俩行代码放这里就会出错,是因为什么?
// var leftMaxBorderSum = rightMaxBorderSum = 0;
// var lefttemp = righttemp = 0;
if(left == right){
if(arr[left] > 0){
return arr[left];
}else{
return 0;
}
}
var center = Math.floor((left + right)/2);
var leftMaxSum = maxSubSum(arr,left,center);
var rightMaxSum = maxSubSum(arr,center+1,right);
//console.log(leftMaxBorderSum,rightMaxBorderSum);
//把代码放这里就不会出错,是因为什么?
var leftMaxBorderSum = rightMaxBorderSum = 0;
var lefttemp = righttemp = 0;
for(var i=center; i>=left; i--){
lefttemp += arr[i];
if(lefttemp >= leftMaxBorderSum){
leftMaxBorderSum = lefttemp;
}
}
for(var j=center+1; j<=right; j++){
righttemp += arr[j];
//console.log(j);
if(righttemp >= rightMaxBorderSum){
rightMaxBorderSum = righttemp;
}
}
console.log('['+left+','+right+']');
console.log(center+','+leftMaxSum+','+rightMaxSum+','+ (leftMaxBorderSum + rightMaxBorderSum));
return Math.max(leftMaxSum,rightMaxSum,(leftMaxBorderSum + rightMaxBorderSum));
}
var arr = [4,-3,5,-2,-1,2,6,-2];
console.log(maxSubSum(arr,0,7));
声明定义语句写在递归调用前,产生的答案是错的。但是声明定义语句写在递归调用后,答案就是正确。我觉得有可能跟作用域链有关系,
但是想不通为什么,求大神给解释解释。