Javascript递归函数返回未定义而不是预期结果

Javascript recursive function returning undefined instead of expected result

本文关键字:结果 递归函数 返回 未定义 Javascript      更新时间:2023-09-26

我在JSFiddle上有以下函数:

function getRandomPointsInRange(range){
        var x1 = rand(1, 40),
            y1 = rand(1, 40),
            x2 = rand(1, 40),
            y2 = rand(1, 40),
            result;
        if(getDistance(x1, y1, x2, y2) < range){
            console.log('test');
            getRandomPointsInRange(range);
        }else{
            result = {x1: x1, y1: y1, x2: x2, y2: y2};
            console.log(result);
            return result;
        }
    }

生成两个距离等于或大于一定距离的点(在本例中为20)。问题是有时函数返回undefined,而不是预期的结果。你不能看到在JS小提琴,但控制台日志显示,函数返回undefined只有当函数调用自己至少一次(当console.log('test')被触发。即使函数返回undefined,结果本身实际上也被定义为一个对象(第二个console.log显示带有点坐标的适当对象)。为什么会发生这种情况,以及如何修复这种情况,以便始终返回适当的对象?

JS提琴链接:https://jsfiddle.net/3naLztoa/2/

Prima vista,你需要另一个return

基本上递归函数在任何出口都需要一个值,如果函数应该返回一个值。如果不指定,则按设计获得undefined

为了防止这种情况,必须返回另一次调用递归函数的值。

function getRandomPointsInRange(range) {
    var x1 = rand(1, 40),
        y1 = rand(1, 40),
        x2 = rand(1, 40),
        y2 = rand(1, 40),
        result;
    if (getDistance(x1, y1, x2, y2) < range) {
        console.log('test');
        return getRandomPointsInRange(range);
       // ^^^^
    } else {
        result = {x1: x1, y1: y1, x2: x2, y2: y2};
        console.log(result);
        return result;
    }
}

@Nina说,你需要另一个return,并打印json JSON.stringify来显示结果:

function getDistance(x1, y1, x2, y2) {
  var result = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
  return result;
};
function rand(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};
function getRandomPointsInRange(range){
		
		var x1 = rand(1, 40),
			y1 = rand(1, 40),
			x2 = rand(1, 40),
			y2 = rand(1, 40),
			result;
			
		if(getDistance(x1, y1, x2, y2) < range){
			return getRandomPointsInRange(range);
		}else{			
			result = {x1: x1, y1: y1, x2: x2, y2: y2};
			return result;
		}
	}
  document.getElementById('result').innerHTML = JSON.stringify(getRandomPointsInRange(20));
<body>
  <p id="result">
  </p>
</body>