简体   繁体   English

将字典中的值设置为 HTML 表 - Javascript

[英]Setting Value from Dictionary To HTML Table - Javascript

I am new to Javascript Dictionary我是 Javascript 词典的新手

I have few mac address in my router web terminal.我的路由器网络终端中的 mac 地址很少。 I am trying to convert mac addresses to name so I had created a dictionary with all the translations.我正在尝试将 mac 地址转换为名称,因此我创建了一个包含所有翻译的字典。 Now when I am logging the value it gives correct result but when I supply it to HTML table.现在,当我记录值时,它给出了正确的结果,但是当我将它提供给 HTML 表时。 Table sets undefined and also log undefined表集 undefined 和 log undefined

The code is below...代码如下...

const macAddressDictionary = {
    "74:C1:7D:C8:E4:D6": "Sunny", 
    "FA:16:11:D3:B7:84": "Kamran Sir",
    "44:5E:CD:B2:91:14": "Usman",
    "20:79:18:F0:DB:9C": "Usman-PC", 
    "66:EA:8E:E5:60:C3": "Arif",
    "F2:74:6E:25:91:B1": "Danish",
}
var table = document.getElementById("staTbl");
for (var i = 0, row; row = table.rows[i]; i++) {  
for (var j = 0, col; col = row.cells[j]; j++) {
    console.log(macAddressDictionary[row.cells[1].innerHTML]);  
    row.cells[1].innerHTML = macAddressDictionary[row.cells[1].innerHTML];
  }  
}

Output;输出;

VM3694:13 undefined
VM3694:13 Sunny
5VM3694:13 undefined
VM3694:13 Kamran Sir
5VM3694:13 undefined
VM3694:13 Usman
5VM3694:13 undefined
VM3694:13 Usman-PC
5VM3694:13 undefined
VM3694:13 Arif
5VM3694:13 undefined
VM3694:13 Danish
5VM3694:13 undefined
undefined

镀铬输出

If I use "if logic" like below.如果我像下面这样使用“if logic”。 It also sets the value in the table.它还设置表中的值。 But I dont know how to achieve this with dictionary但我不知道如何用字典来实现这个

for (var j = 0, col; col = row.cells[j]; j++) {
if (row.cells[1].innerHTML == "74:C1:7D:C8:E4:D6") {
 row.cells[1].innerHTML = "Sunny";
  }
}

在此处输入图像描述

In essense what you are doing is looking at each column of the table and check if the content of that column exists in the dictionary, it is normal it is normal that you get 6 console logs (the amount of keys stored in the dictionary) and 40 + undefined because the rest of the keys don't exist in the dictionary本质上你正在做的是查看表的每一列并检查该列的内容是否存在于字典中,这是正常的,你得到6 console logs (存储在字典中的键的数量)和40 + undefined ,因为字典中不存在其余键

the easiest thing you can do this is check if they key exists in the dictionary您可以做的最简单的事情是检查字典中是否存在键

const has = Object.prototype.hasOwnProperty
const table = document.getElementById("staTbl");
for (let i = 0, row; row = table.rows[i]; i++) {  
    for (var j = 0, col; col = row.cells[j]; j++) {
    
    // check if dictionary has the key
     if (has.call(macAddressDictionary,row.cells[1].innerHTML)) {
      row.cells[1].innerHTML = macAddressDictionary[row.cells[1].innerHTML]
     }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM