【问题标题】:JavaScript .map using multiple array sources使用多个数组源的 JavaScript .map
【发布时间】:2021-01-15 14:50:16
【问题描述】:

我有一个提供 4 个值的测试:

fPortTotal = 防火墙测试中有多少端口的数字。

fProtocol = 包含端口协议的数组(例如 UDP、TCP)

fPorts = 带有什么端口号的数组

fStatus = 根据端口打开或关闭的数组

在所有数组中,[0] 是第一个端口,[1] 是第二个端口,依此类推。 我想使用 .map 方法在<p> 中显示每个端口的信息。问题是我很难理解 .map 方法以及如何使用它。我相信函数的“骨架”应该是这样的:

function populateFw(fPorts, fStatus, fPortTotal, fProtocol) {
    var output = document.getElementById('firewallRes');
    var text = document.createElement ('p');
    text.id = 'firewallEndResults';
    text.innerHTML = arrayOfArrays.map;
}

任何帮助将不胜感激。

【问题讨论】:

  • 我知道arrayOfArrays.map 在这一点上是没用的
  • 拥有单独的数组是让这变得困难的原因。为什么没有像[{ fPort: 80, fProtocol: "TCP", fStatus: "Open" }, ...] 这样的一组对象?
  • .map 回调函数获取索引作为第二个参数,因此您可以执行fPorts.map((fport, index) => doSomething(fport, fStatus[index], fPortTotal[index], fProtocol[index]) 之类的操作 - 在 doSomething 中执行的操作取决于您
  • @phil 提供给我的程序是导致单独数组的原因,不幸的是,我无法控制它。

标签: javascript arrays array.prototype.map


【解决方案1】:

这样做:

for(i=0; i<fPorts; i++){
  var text = document.createElement ('p');
  text.id = `firewallEndResults${i}`;
  text.innerHTML = `${fStatus[i]}, ${fPortTotal[i]}, ${fProtocol[i]}`;
  somediv.appendChild(text); // don't forget  
}

map 是改变数组项的函数,需要回调

const newArray = arrayOfArrays.map(callback)

const newArray = arrayOfArrays.map((i)=>{ 在循环中做某事})

如果你使用 React,你可以在 JSX 中使用 map,但这是另一回事

【讨论】:

  • 你不是说我
【解决方案2】:

ForEach 在这里会更好。 Map 返回一个对象,你不需要它。

fStatus.forEach((_, index)=>{
  //then using index acces all the information
  const protocol = fProtocol[index];
  const protNumber = fPorts[index]
  ....
  text.innerHTML += 'Protocol is '+protocol+' and port number is '+protNumber;
});

编辑:Talmacel Marian Silviu 的例子也基本相同。

【讨论】:

  • 是的,我同时在写它:)
  • 什么是_引用?我还在理解数组:)
  • 使用了 _ 是因为他没有使用最终解决方案中的状态,也可以命名为状态,然后您可以在您正在创建的字符串中添加状态。
  • status 在这种情况下,我只使用了_,因为我不打算在示例中使用这个参数
  • 是的,你可以给它起任何名字...... forEach 接收的回调函数中的第一个名字将从第一个元素开始一个一个地获取数组中每个元素的值并循环遍历它们直到最后
【解决方案3】:

你可以试试这样的:

function populateFw(fPorts, fStatus, fPortTotal, fProtocol) {
    var output = document.getElementById('firewallRes');
    fPorts.forEach((port, index) => {
       const text = document.createElement('p');
       text.innerText= `${port}: ${fProtocol[index]} - ${fStatus[index]}`;
       output.appendChild(text);
    })
}

【讨论】:

  • 我没有经验的眼睛告诉我这是在使用 Jquery?
  • no jquery ...您看到的美元符号是因为我使用模板文字作为字符串。查一下:)
  • 好的,谢谢大家。这对我来说可能已经足够了。
  • @Talmachel Marian Silviu 目前正在尝试将每个 fStatus 值的打印值从 1/0 更改为打开/关闭和彩色文本。你对我怎么做有什么建议吗?
  • 从真假变为1和0可以这样,text.innerText=${port}: ${fProtocol[index]} - ${fStatus[index]? 1 : 0}; -> 至于样式应该是另一个问题的主题。
猜你喜欢
  • 1970-01-01
  • 2019-06-09
  • 2017-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-10
相关资源
最近更新 更多