我有一个程序,查看两点并与他们进行操作。我需要始终确保点的顺序是正确的。我需要第一点成为两者中较小的一个。我正在尝试编写一个实用程序函数,我可以在其他函数中调用该函数来重新排序传入的参数。任何帮助理解为什么这种方法不起作用会很棒!生病尽我所能,只贴相关的代码如何更改外部函数参数
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);
内部函数是在另一个函数内部定义的函数 - 互补的,外部函数是该函数定义的函数。你在你的代码中没有任何这些。你可能想要的是通过引用“传递参数”,但JavaScript不支持这种亵渎 – nekavally