gpt4 book ai didi

javascript - 如何更改外部函数参数

转载 作者:行者123 更新时间:2023-11-29 21:32:08 25 4
gpt4 key购买 nike

我有一个程序可以查看两个点并对它们进行操作。不过,我需要始终确保这些点的顺序正确。我需要第一个点是两者中较小的一个。我正在尝试编写一个实用程序函数,我可以在其他函数内部调用它来重新排序传入的参数。任何有助于理解为什么这不起作用的帮助都会很棒!我会尽力只发布相关代码

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);

最佳答案

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.
(....)

关于javascript - 如何更改外部函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35903721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com