Javascript 如何更改外部函数参数
我有一个程序,它关注两点并对它们进行操作。但我需要始终确保各点的顺序正确。我需要第一个点是两者中较小的一个。我正在尝试编写一个实用函数,可以在其他函数内部调用该函数,以对传入的参数重新排序。任何有助于理解为什么这不起作用的帮助都将是惊人的!我会尽力只发布相关代码Javascript 如何更改外部函数参数,javascript,Javascript,我有一个程序,它关注两点并对它们进行操作。但我需要始终确保各点的顺序正确。我需要第一个点是两者中较小的一个。我正在尝试编写一个实用函数,可以在其他函数内部调用该函数,以对传入的参数重新排序。任何有助于理解为什么这不起作用的帮助都将是惊人的!我会尽力只发布相关代码 var unionFind = { data: [], //This will be filled by a later function reorderPoints: function(num1, num2) {
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);
var unionFind={
数据:[],//这将由以后的函数填充
reorderPoints:函数(num1,num2){
//用于确保点的顺序正确的实用工具
//我们将始终保留较小的数字以显示是否有积分
//它们是相互联系的。
如果(num1>num2){
调试器;
点1=num2;
点2=num1;
}
},
并集:函数(点1、点2){
这是重新定义点(点1,点2);
//如果两点已连接
//然后返回true
if(this.connected(point1,point2)==true){
返回true;
}
//否则,循环遍历数据数组并
//更改连接到的所有条目
//第一个点指向第一个点的值
//点
对于(var i=0;i 对于union
方法point1
和point2
中的(var i=0;i是参数,因此它们是局部变量。当您输入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.
(....)
哦,我明白了,我以为我在这里完成了一个闭包!但是因为函数不是在外部函数中创建的,所以它没有访问它的变量的权限。内部函数是在另一个函数中定义的函数-互补的,外部函数是在其中定义这个函数的函数。你的代码中根本没有这些函数。你在做什么我希望“通过引用”传递参数,但JavaScript不支持这种亵渎