2016-03-09 63 views
2

我有一个程序,查看两点并与他们进行操作。我需要始终确保点的顺序是正确的。我需要第一点成为两者中较小的一个。我正在尝试编写一个实用程序函数,我可以在其他函数中调用该函数来重新排序传入的参数。任何帮助理解为什么这种方法不起作用会很棒!生病尽我所能,只贴相关的代码如何更改外部函数参数

var unionFind = { 
    data: [],  //This will be filled by a later function 
    reorderPoints: function(num1, num2) { 
    // useful utility to make sure points are in proper order 
    // we will always keep the smaller number to show if points 
    // are connected. 
    if(num1 > num2) { 
     debugger; 
     point1 = num2; 
     point2 = num1; 
    } 
    }, 
    union: function(point1, point2) { 
    this.reorderPoints(point1, point2); 
    // if the two points are already connected 
    // then just return true 
    if(this.connected(point1, point2) === true) { 
     return true; 
    } 
    // otherwise loop through the data array and 
    // change all entries that are connected to 
    // the first point to the value of the first 
    // point 
    for(var i = 0; i < this.data.length; i++) { 
     if(this.data[i] === point2) { 
     this.data[i] = point1; 
     } 
    } 
    }, 

    connected: function() { 
    this.reorderPoints(point1, point2); 
    return this.data[point1] === this.data[point2]; 
    }, 
    initData: function(num) { 
    for(var i = 0; i <= num; i++) { 
     this.data[i] = i; 
    } 
    } 
}; 

unionFind.initData(9); 
console.log(unionFind.data); 

unionFind.union(4,3); 
console.log(unionFind.data); 
+0

内部函数是在另一个函数内部定义的函数 - 互补的,外部函数是该函数定义的函数。你在你的代码中没有任何这些。你可能想要的是通过引用“传递参数”,但JavaScript不支持这种亵渎 – nekavally

回答

2

union方法point1point2是参数,所以他们是局部变量。当你进入reorderPoints方法不存在在那里,所以这段代码:

point1 = num2; 
point2 = num1; 

刚刚创造了新的point1point2变量(因为没有var之前这段时间全球的)。

为了解决这个问题,你需要有point1point2在这两个功能之外的命名空间可变因素声明或者你可以构造这两个点的阵列和阵列传递给排序方法,像这样:

reorderPoints: function(points) { 
    if(points[0] > points[1]) { 
     var tmp = points[0]; 
     points[0] = points[1]; 
     points[1] = tmp; 
    } 
    }, 
    union: function(point1, point2) { 
    var points = [point1, point2]; 
    this.reorderPoints(points); 
    // From this line you should use points[0] and points[1] as sorted points 
    // because point1 and point2 parameters are not changed. 
    (....) 
+0

哦,我看到我以为我在这里拉封闭!但由于函数不是在外部函数中创建的,因此它无法访问其变量。 –

相关问题