JavaScript字典值写入HTML表格时出现undefined问题求助
问题:用字典替换HTML表格中MAC地址时出现undefined
我是JavaScript字典新手,在路由器Web终端里有多个MAC地址,想通过创建的字典把MAC地址转换成对应名称。日志能输出正确结果,但写入HTML表格时出现undefined,控制台也打印undefined。用if逻辑能实现需求,但想知道怎么用字典正确完成。
错误代码
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]; } }
控制台输出
VM3694:13 undefined VM3694:13 Sunny VM3694:13 undefined VM3694:13 Kamran Sir VM3694:13 undefined VM3694:13 Usman VM3694:13 undefined VM3694:13 Usman-PC VM3694:13 undefined VM3694:13 Arif VM3694:13 undefined VM3694:13 Danish VM3694:13 undefined undefined
问题原因
你的代码嵌套了两层循环:外层遍历表格行,内层遍历每行的所有单元格。这会导致每一行的每个单元格都会触发一次MAC地址替换操作。
第一次替换时,单元格内容从MAC地址变成了名称(比如Sunny),后续循环再访问这个单元格时,字典里没有"Sunny"这个键,自然就返回undefined,同时把单元格内容改成undefined。另外,你其实只需要处理每行的第2个单元格(索引1),完全没必要遍历所有单元格。
修正后的代码
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", }; const table = document.getElementById("staTbl"); // 只遍历表格的每一行,不需要遍历单元格 for (let i = 0; i < table.rows.length; i++) { const row = table.rows[i]; const macCell = row.cells[1]; // 去除MAC地址前后可能存在的空格,避免匹配失败 const macAddress = macCell.innerHTML.trim(); // 先检查字典里有没有这个MAC地址,再替换 if (macAddressDictionary.hasOwnProperty(macAddress)) { macCell.innerHTML = macAddressDictionary[macAddress]; console.log(macAddressDictionary[macAddress]); } else { // 可选:处理不在字典中的MAC地址,避免控制台输出undefined console.log(`未找到对应名称的MAC地址: ${macAddress}`); } }
关键修正点
- 移除了内层遍历单元格的循环,直接定位到每行的第2个单元格(索引1)
- 增加
trim()处理,防止MAC地址前后有空格导致字典匹配失败 - 用
hasOwnProperty()检查键是否存在,避免undefined被写入表格和控制台 - 用
let替代var,避免变量提升带来的潜在问题
内容的提问来源于stack exchange,提问作者Usman Khawar
相关产品推荐
相关产品推荐

