如何更改外部函数参数
How to change outer functions arguments
>我有一个程序,它查看两个点并用它们进行操作。不过,我需要始终确保点的顺序正确。我需要第一点是两者中较小的一点。我正在尝试编写一个实用程序函数,我可以在其他函数内部调用该函数以对传入的参数进行重新排序。任何有助于理解为什么这不起作用的帮助都会很棒!我尽力只发布相关代码
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
方法中,point1
和point2
是参数,因此它们是局部变量。当你输入reorderPoints
方法时,它们在那里不存在,所以这段代码:
point1 = num2;
point2 = num1;
只是创建新的point1
并point2
变量(这次是全局变量,因为之前没有var
)。
要解决此问题,您需要在这两个函数之外的命名空间中声明point1
和point2
变量,或者您可以构造这两个点的数组并将该数组传递给排序方法,如下所示:
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.
(....)
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- AngularJS:我可以跳过函数参数回调吗
- 函数未将值作为参数传递
- JS:检查URL中的参数,然后迭代一个参数为var的函数
- 为什么不'我们在javascript中使用函数参数的数据类型
- 你好,这是测试用例,我必须在函数中传递n个参数
- JavaScript - 多参数函数,它是多个图像库的字符串
- 如何从两个参数函数返回随机整数
- 以无点风格在Ramda中编写一个无参数函数
- JS:将单参数函数转换为可链接函数
- 正则表达式类似于Javascript中的参数函数
- 将 $' 值传递给替换的关联参数函数
- "这个“;在参数函数中
- 如何向jquery插件发送参数函数
- 将参数函数Node.js从一个js传递到另一个js
- 如何在javascript参数函数中传递PHP post方法字符串
- 装饰 Javascript Promise.then 以便参数函数接收附加参数
- 正在分析setInterval ID'是的's参数函数
- 如何根据一个参数函数计算年龄
- 对象参数/函数和/或三元运算符混淆