首页 > 解决方案 > 函数的结果是未定义的而不是对象

问题描述

当我调用下面的函数maxSubArraySum时,它不会返回我希望这样做的对象arrSlice 。相反,当我在 chrome 开发人员工具中运行代码时,我得到未定义的结果。

function maxSubArraySum(array, count) {
  var slicePoint1;
  var slicePoint2 = count;
  var arrSlice = {};
  var pH;

  for (var i = 0; i < array.length; i++) {
      slicePoint1 = i;
      pH = array.slice(slicePoint1, slicePoint2);
      if(pH.length<count){
      	return;
      }
      arrSlice[i] = pH;
      slicePoint2 += 1;
     
  }//End of loop

  console.log(arrSlice);
  return arrSlice;
}

maxSubArraySum([1, 2, 3, 4, 5, 6, 7, 8, 9], 4);

标签: javascript

解决方案


你需要检查这个条件

if(pH.length<count){
        return;
      }

空返回语句返回未定义,我在下面粘贴了调试代码,请详细说明您的问题,以便我更正它

function maxSubArraySum(array, count) {
  var slicePoint1;
  var slicePoint2 = count;
  var arrSlice = {};
  var pH;
console.log(arguments);
  for (var i = 0; i < array.length; i++) {
    slicePoint1 = i;
      pH = array.slice(slicePoint1, slicePoint2);
      if(pH.length<count){
        console.log("dsf");return;
      }
      arrSlice[i] = pH;
      slicePoint2 += 1;

  }//End of loop

  console.log("sdf",arrSlice);
  return arrSlice;
}

maxSubArraySum([1, 2, 3, 4, 5, 6, 7, 8, 9], 4);

推荐阅读