【问题标题】:JS merge 2 arrays and their individual values from a single index into a single index in 1 arrayJS 将 2 个数组及其单个索引中的单个值合并为 1 个数组中的单个索引
【发布时间】:2016-01-29 16:59:07
【问题描述】:

我想知道如何使用下面的代码实现上述目标。因此,例如,当数据被连接时,我将在新数组中的索引中组合结果类似于 [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);
}

【问题讨论】:

  • var lastSeenAt = {x: null, y: null}; 造成了我猜的麻烦。将其移出该功能。否则,您只需尝试计算 Math.pow(null - somenumer, 2)
  • 谢谢,但实际上我想知道如何在问题中实现上述逻辑。
  • 那么prevX, prevY, totalTravelled 在哪里,看不到它们在您的代码中的使用位置。
  • 我的错,那些不应该在那里。

标签: javascript arrays function join indexing


【解决方案1】:

您可以将 lastSeenAt 的 init 移出函数。并在函数末尾分配新值。

要获得组合结果,请使用mouseDistancetimers 中的较短者,并将数据推送到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]];
  }
}

【讨论】:

  • 谢谢你。虽然我真正需要的是如何将 timers 数组的一个索引中的数据加上 mouseDistance 数组的一个索引中的数据合并到一个名为 combineresults 的新数组中的一个索引中。
  • 你的意思是,你想让你的函数也做combinedresults[n] = timers[n] * mouseDistance[n] ?
  • 是的,如果 timers 数组的值为 2.62,mousedistance 数组的值为 500,我想将这两个数据放入一个数组中,例如 [2.62, 500 ],谢谢!
  • 这是在另一个函数上完成的,还是您希望在printMousePos 中完成?另外,我们能否保证timersmouseDistance的长度相同,或者combinedresults的长度等于它们中的任何一个?
  • 在另一个函数中。是的,combinedresults 的长度将取决于数组计时器和 mouseDistance 的长度,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-03
  • 1970-01-01
  • 1970-01-01
  • 2019-05-29
  • 2018-06-07
相关资源
最近更新 更多