JavaScript select 同一行,多列 (CSV)

JavaScript select same row, multi columns (CSV)

这是P5.js,这是一个非常愚蠢和简单的问题。 https://editor.p5js.org/kornfusion/sketches/5xtb88Ntn

  for (let i = 0; i < table.getRowCount(); i++){
    for (let j = 0; j < table.getRowCount(); j++){
    if (table.getRow(i).arr[1] = '00:11:1F:AC:ba:39') {
      j = table.getRowCount(i).length;
      textSize(155);
      text(table.getRow(i).arr[2], 400, 540);
    }
  }
}

我正在尝试将 mac 地址与 IP 匹配。如果它们匹配,则将它们放在圆圈旁边。圆圈已经在草图中,我只需要 CSV 文件中的数据并遍历每一行以找到 MAC.

描述与代码混淆。

I'm trying to match the mac address with IP. and if they matched put them beside the circle.

您的意思是将 MAC 地址的一部分与 IP 地址的一部分匹配吗?

示例中的 MAC 地址如下所示:00:11:1f:10:11:13.

您示例中的 IP 地址如下所示:10.11.2.1.

你的意思是比较跨行不相同的部分(例如 00:11:1f:10:11:13 到 10.11.2.1 )?

您的情况表明并非如此:

if (table.getRow(i).arr[1] = '00:11:1F:AC:ba:39')

它尝试匹配具有 MAC 地址 00:11:1F:AC:ba:39 的任何行。 请注意,arr[1] 指向第二个 CSV 列:“模型”。 MAC 地址是第四列(索引 3(例如 table.getRow(i).arr[3])) 或者你可以通过列名检索它,因为 CSV 有一个 header:

table.getRow(i).obj["MAC address"]

如果您要遍历所有行,则单个 for 循环应该执行。 此外,您需要处理 MAC 地址不在列表中的边缘情况。

例如

  let foundIP = null;
  for (let i = 0; i < table.getRowCount(); i++){
      let currentRow = table.getRow(i);
      if (currentRow.obj['MAC address'] === '00:11:1F:AC:ba:39'){
        foundIP = currentRow.obj['IP address'];
        break;
      }
    }

  
  if(foundIP){
    console.log('foundIP',foundIP);
  }else{
    console.log('no IP found for MAC 00:11:1F:AC:ba:39');
  }

注意:

  • currentRow 是 re-used(与每个循环调用 table.get() 多次不同):这是值得的,尤其是当您必须处理许多行时
  • 在 JS == 中有效,但建议使用 ===,因为它还会检查数据类型是否匹配
  • break 用于在找到匹配项后跳出 for 循环。 (如果没有找到行将没有有效值)

这可以很容易地封装在一个 re-usable 函数中:

function findIP(table, macAddress) {
  for (let i = 0; i < table.getRowCount(); i++) {
    let currentRow = table.getRow(i);
    if (currentRow.obj['MAC address'] === macAddress) {
      return currentRow.obj['IP address'];
    }
  }
}

在这种情况下,结果是 IP(如果找到)或 undefined(如果未找到匹配项):

  let macToFind = '00:11:1F:AC:ba:39'
  let foundIP = findIP(table, macToFind);

  if (foundIP) {
    console.log('foundIP', foundIP);
  } else {
    console.log('no IP found for MAC ' + macToFind);
  }

这应该使其足够灵活,可以在需要时搜索多个表和 mac 地址。