从双重功能中获取变量

时间:2018-11-23 12:48:45

标签: javascript

已经有一个相同问题的帖子,但是没有一个答案在做我想做的事情。所以这是代码示例:

function findIP(onNewIP) {
  var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
  var pc = new myPeerConnection({
      iceServers: [{
        urls: "stun:stun.l.google.com:19302"
      }]
    }),
    noop = function() {},
    localIPs = {},
    ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
    key;

  function ipIterate(ip) {
    if (!localIPs[ip]) onNewIP(ip);
    localIPs[ip] = true;
  }

  pc.createDataChannel("");

  pc.createOffer(function(sdp) {
    sdp.sdp.split('\n').forEach(function(line) {
      if (line.indexOf('candidate') < 0) return;
      line.match(ipRegex).forEach(ipIterate);
    });
    pc.setLocalDescription(sdp, noop, noop);
  }, noop);

  pc.onicecandidate = function(ice) {
    if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
    ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
  };
}

该代码是JS函数,之后是用法:

function addIP(ip) {
  var li = document.createElement('li');
  li.textContent = ip;
  document.getElementById("IPLeak").appendChild(li);
}

findIP(addIP);

所以这种用法的作用是将所有3个ip(本地,本地ip6和公共ip4)并使用li元素显示。但是,我需要的只是一个ip地址(公共ip4),它需要被存储到变量中,以便我可以进一步处理它。在这种情况下,需要将其取出的变量是函数addIP(ip)中的ip变量。

我确实找到了一个可以在函数外部获取变量的代码示例:

<script>
function profileloader()
{
    profile = []; // no "var" makes this global in scope
    profile[0] = "Joe";
    profile[1] = "Bloggs";
    profile[2] = "images/joeb/pic.jpg";
    profile[3] = "Web Site Manager";
}
profileloader();
document.write("Firstname is: " + profile[0]);
</script>

但是当我尝试实现时,问题是它如何与单个函数一起工作,而在代码中有函数执行函数,因此我无法获得变量输出。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您需要了解回调https://developer.mozilla.org/en-US/docs/Glossary/Callback_function

您的函数findIP接受了一个回调,该回调使用ip多次调用该函数,因此例如记录您可以调用的所有ip

findIP(function(ip){console.log(ip)});
相关问题