我想知道如何使用下面的代码实现上述目标。因此,例如,当数据被连接时,我将在新数组中的索引中得到类似[2.62,460]的结果。当用户单击按钮时,下面的两个函数都通过事件侦听器调用。非常感谢任何帮助,谢谢。
var mouseDistance = new Array();
var timers = new Array();
var combinedresults = new Array();
//THIS FUNCTION CALCULATES THE DISTANCE MOVED
function printMousePos(e) {
var lastSeenAt = {
x: null,
y: null
};
var cursorX = e.clientX;
var cursorY = e.clientY;
var math = Math.round(Math.sqrt(Math.pow(lastSeenAt.y - cursorY, 2) +
Math.pow(lastSeenAt.x - cursorX, 2)));
mouseDistance.push(math);
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
timers.push(t);
}
答案 0 :(得分:1)
您可以将lastSeenAt
的init移出该功能。并在函数末尾指定新值。
要获得综合结果,请使用mouseDistance
和timers
中的较短者,并将数据推送到combinedresults
应该有效。
var mouseDistance = new Array();
var timers = new Array();
var combinedresults = new Array();
// Init with both is null.
var lastSeenAt = {
x: null,
y: null
};
//THIS FUNCTION CALCULATES THE DISTANCE MOVED
function printMousePos(e) {
var cursorX = e.clientX;
var cursorY = e.clientY;
// Don't calculate when x, y is null, which is the first time.
// Or you can give lastSeen some other initValue rather than (null, null).
if (lastSeenAt.x !== null) {
var math = Math.round(Math.sqrt(Math.pow(lastSeenAt.y - cursorY, 2) +
Math.pow(lastSeenAt.x - cursorX, 2)));
mouseDistance.push(math);
}
// Keep the x,y value.
lastSeenAt.x = cursorX;
lastSeenAt.y = cursorY;
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
timers.push(t);
}
// get combinedresults
function getCombinedResult() {
// Get the shorter length.
var length = Math.min(mouseDistance.length, timers.length);
var i;
//
for (i = 0; i < length; ++i) {
combinedresults[i] = [timers[i], mouseDistance[i]];
}
}