我有一个程序可以查看两个点并对它们进行操作。我需要始终确保这些点的顺序正确。我需要第一点是两者中较小的一点。我正在尝试编写一个实用程序函数,我可以在其他函数中调用它来重新排序传入的参数。任何帮助理解为什么这不起作用将是惊人的!我会尽力发布相关代码
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 :(得分:2)
在union
方法point1
和point2
是参数,因此它们是局部变量。当您输入reorderPoints
方法时,它们不存在,所以此代码:
point1 = num2;
point2 = num1;
只需创建新的point1
和point2
变量(这次是全局变量,因为之前没有var
)。
要解决此问题,您需要在这两个函数之外的命名空间中声明point1
和point2
变量,或者您可以构造这两个点的数组并将该数组传递给sort方法,像这样:
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.
(....)