我正在为一本动力系统书做一个捕食者-猎物模型。我首先为初始条件创建一个可拖动点。如果我设置了第二个点,它的坐标是第一个点的函数,我可以拖动一个点,它就会移动另一个点。我试图得到系统的100点轨道,但我遇到了困难。这里有一个适用于单点的小提琴-- https://jsfiddle.net/jford1906/gx86vbtc/21/
var board = JXG.JSXGraph.initBoard('jxgbox', {
boundingbox: [-0.1, 3, 1, -0.1],
axis: true,
grid: true,
showFullscreen: true
});
var p1 = board.create('point', [0.5, 0.5], {
name: 'A'
});
var coords = board.create('text',
[0.3, 2.8, function() {
return "Initial Condition: (" + JXG.toFixed(p1.X(), 2) + "," + JXG.toFixed(p1.Y(), 2) + ")";
}]
);
var p2 = board.create('point', [function() {
return 2 * p1.X() * (1 - p1.X()) - 0.5 * p1.X() * p1.Y()
}, function() {
return 4 * p1.Y() / 5 + 1.5 * p1.X() * p1.Y()
}], {
withLabel: false,
color: "blue",
opacity: 1,
size: 3
});到目前为止,我已经尝试将轨道的每个点插入到一个数组中,并让下一个点为它的坐标运行与我在工作示例中相同的函数。它最初显示了整个轨道,但当我移动初始条件时,除了轨道中的最后一个点之外,所有点都消失了。这个小提琴展示了我是如何尝试去做的-- https://jsfiddle.net/jford1906/jra9g2d3/3/
var i; //indexing variable
var pts = [p1] //Put the initial condition in an array
for (i = 1; i < 100; i++) {
var p2 = board.create('point', [function() {
return 2 * pts[i - 1].X() * (1 - pts[i - 1].X()) - 0.5 * pts[i - 1].X() * pts[i - 1].Y()
}, function() {
return 4 * pts[i - 1].Y() / 5 + 1.5 * pts[i - 1].X() * pts[i - 1].Y()
}], {
withLabel: false,
color: "blue",
opacity: 1,
size: 1
});
pts.push(p2);
}关于为什么会发生这种情况的想法,还是对不同方法的想法?我还尝试将整个循环放在一个函数中,并在拖动点时使用触发器,但同样的问题也发生了。
发布于 2021-01-04 18:39:58
这是JavaScript闭包的一个问题。该问题已在https://groups.google.com/g/jsxgraph/c/Y1y1Mbd23ZQ中得到回答。一个非常快速的解决办法是用let而不是var来定义变量i
var pts = [p1] //Put the initial condition in an array
for (let i = 1; i < 100; i++) {
var p2 = board.create('point', [function() {
return 2 * pts[i - 1].X() * (1 - pts[i - 1].X()) - 0.5 * pts[i - 1].X() * pts[i - 1].Y()
}, function() {
return 4 * pts[i - 1].Y() / 5 + 1.5 * pts[i - 1].X() * pts[i - 1].Y()
}], {
withLabel: false,
color: "blue",
opacity: 1,
size: 1
});
pts.push(p2);
}https://stackoverflow.com/questions/65532948
复制相似问题