javascript - 在 Javascript 中识别一维数组的边缘情况

标签 javascript arrays d3.js graph

我正在创建一个二维热图,当您点击任何像素时它就会起作用。它获取与每个像素(包括相邻像素)的索引关联的数据并绘制它。目前看起来像这样:

enter image description here

我遇到的问题是当我点击左边缘或右边缘像素时,因为它从相邻像素抓取数据,所以它可以从图形的另一侧检索数据,因为它都在一维范围内大批。我正在尝试创建一个条件来检查单击的像素是否是边缘情况,然后相应地配置放大图以不显示主图另一侧的点。这是我到目前为止的代码:

// pushes all dataMagnified arrays left and right of i to magMainStore
var dataGrabber = function(indexGrabbed, arrayPushed) {

  // iterates through all 5 pixels being selected
  for (var b = -2; b <= 2; b++) {

    var divValue = toString(i / cropLength + b);

    // checks if selected index exists, and if it is not in the prior row, or if it is equal to zero
    if (dataMagnified[indexGrabbed + b] != undefined && (& divValue.indexOf(".")!=-1)) {
      dataMagnified[indexGrabbed + b].forEach(function(z) {
        arrayPushed.push(z);
      })
    }
  }
};

我试图获得与二维数组相同的结果,并查找何时未定义单个数组中的相邻值。这是我为此创建条件的行

if (dataMagnified[indexGrabbed + b] != undefined && (& divValue.indexOf(".")!=-1)) {

and 之后的第二个条件是我迄今为止试图解决这个问题的尝试。我不确定我是否可以在迭代 5 次的 for 循环中执行此操作,或者我是否必须为此创建多个条件。此外,这是一张显示我正在尝试做的事情的图片:

enter image description here

谢谢!

最佳答案

您的方法看起来过于复杂并且执行起来相当缓慢。例如,为了检查整数而将数字转换为字符串以便能够使用 .indexOf() 查找小数点似乎并不正确。

一个更简单和更优雅的解决方案可能是以下函数,它将返回受行限制限制的选择范围:

function getBoundedSelection(indexGrabbed, selectionWidth) {
  return dataMagnified.slice(
    Math.max(Math.floor(indexGrabbed/cropLength) * cropLength, indexGrabbed - selectionWidth),
    Math.min(rowStartIndex + cropLength, indexGrabbed + selectionWidth)
  );
}

这里,为了尽可能保持灵 active ,selectionWidth 确定所选范围到 indexGrabbed 任一侧的宽度。在您的情况下,这将是 2

为了解释它的作用,我将其分解:

function getBoundedSelection(indexGrabbed, selectionWidth) {
    // Calculate the row indexGrabbed is on.
    var row = Math.floor(indexGrabbed/cropLength);

    // Determine the first index on that row.
    var rowStartIndex = row * cropLength;

    // Get the start index of the selection range or the start of the row,
    // whatever is larger.
    var selStartIndex = Math.max(rowStartIndex, indexGrabbed - selectionWidth);

    // Determine the last index on that row
    var rowEndIndex = rowStartIndex + cropLength;

    // Get the end index of the selection range or the end of the row,
    //whatever is smaller.
    var selEndIndex = Math.min(rowEndIndex, indexGrabbed + selectionWidth);

    // Return the slice bounded by the row's limits.
    return  dataMagnified.slice(selStartIndex, selEndIndex);  
}

关于javascript - 在 Javascript 中识别一维数组的边缘情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38796671/

相关文章:

javascript - 获取 d3 轴刻度线以将中心与图形点对齐

javascript - D3.js - 单击节点后无法设置节点标签?

javascript - d3 v4 : merge enter and update selections to remove duplicate code

javascript - 从具有不同域的 iframe 内部进行 AJAX 调用

javascript - 在 Javascript 循环内运行 exec()

java - 无法声明包含多个元素的数组

java - 如何查找数组中重复的元素?

javascript - 如何将 json 对象插入 Google 图表线

javascript - 使用 Javascript 提交表单不适用于新添加的 &lt;input&gt;

javascript - 如何在 JavaScript 中对多维对象进行排序