javascript - JavaScript选择同一行,多列(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。
解决方案
描述与代码一起令人困惑。
我正在尝试将 MAC 地址与 IP 匹配。如果它们匹配,则将它们放在圆圈旁边。
您是说将 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 有一个标题:
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');
}
请注意:
table.get()
currentRow 被重复使用(而不是在每个循环中多次调用):这很有价值,尤其是当您必须处理许多行时- 在 JS 中
==
有效,但===
建议使用,因为它还会检查数据类型是否匹配 break
用于在找到匹配项后跳出 for 循环。(如果还没有 foundRow 将没有有效值)
这可以很容易地封装在一个可重用的函数中:
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 地址。
推荐阅读
- java - Java解析和计算文本文件
- r - 在 R 中保持类分布随机抽样
- java - 在 ExecutorService.submit 之后未调用 Java Runnable 实例上的 Run 方法
- hadoop - 如何根据连接列的条件连接配置单元表
- javascript - 2 setInterval() 实例正在运行,如何运行一个?
- git - GitKraken 与 git-crypt 的互操作性
- pandas - 如何在具有唯一键和序列值的列中唯一求和
- postgresql - 使用 CanCanCan 进行不区分大小写的搜索?
- django - Paypal - 将订单保存到数据库的最佳时间是什么时候
- docker - 码头集装箱内关闭的端口