简体   繁体   English

如何从嵌套的 javascript function 返回一个值?

[英]How to return a value from nested javascript function?

window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;  
var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};      
pc.createDataChannel("");   
pc.createOffer(pc.setLocalDescription.bind(pc), noop);        
pc.onicecandidate = function(ice){ 
  if(!ice || !ice.candidate || !ice.candidate.candidate)  return;
  ice.candidate.candidate.split('\r\n').forEach(function (line) {   
    if (line.indexOf("candidate")!==-1) {           
      var parts = line.split(' '),             
      addr = parts[4],
      type = parts[7];
      if (type === 'host') {
        console.log(addr);
        return addr;
      }
    } 
  });
  pc.onicecandidate = noop;
};

In the above javascript, the console.log(addr) works but not the return.在上面的 javascript 中,console.log(addr) 有效,但返回无效。 Please point me where I am doing wrong.请指出我做错了什么。 I tried to wrap this in a function and that doesn't work it either.我试图将它包装在 function 中,但这也不起作用。

As long as your code in synchronous, you can write variables outside of the immediate function scope like so:只要您的代码同步,您就可以在立即数 function scope 之外编写变量,如下所示:

let result = null;
ice.candidate.candidate.split('\r\n').forEach(function (line) {   
    if (line.indexOf("candidate")!==-1) {           
      var parts = line.split(' '),             
      addr = parts[4],
      type = parts[7];
      if (type === 'host') {
        console.log(addr);
        // Save value
        result = addr;
      }
    } 
  });
// ...
console.log(result);

This can be further improved by using a for (let.. of..) loop and break to stop the loop after finding the value you're looking for.这可以通过使用for (let.. of..)循环和break在找到您要查找的值后停止循环来进一步改进。

You should also consider Array.prototype.find() for this.您还应该为此考虑Array.prototype.find()

pc.onicecandidate = function(ice){ 
  if(!ice || !ice.candidate || !ice.candidate.candidate)  return;

  const hosts = [];

  ice.candidate.candidate.split('\r\n').forEach(function (line) {   
    if (line.indexOf("candidate")!==-1) {           
      var parts = line.split(' '),             
      addr = parts[4],
      type = parts[7];
      if (type === 'host') {
        console.log(addr);

        hosts.push(addr)

      }
    }
  });
  pc.onicecandidate = noop;
  
  return hosts;
};

Is something like that what you are after?你追求的是那种东西吗?

You want to return each host address?你想返回每个主机地址吗?

This stores the hosts locally.这将主机存储在本地。 Foreach is synchronous so when it has completed working on the collection then your function will reach the return statement. Foreach 是同步的,因此当它完成对集合的处理时,您的 function 将到达返回语句。

If you want to find the first address then you might want to use.find instead of.forEach, or check that a value exists and bail from the forEach when it does (note that you're still calling that function on each item, it'll just return straight away).如果你想找到第一个地址,那么你可能想使用.find 而不是.forEach,或者检查一个值是否存在并在它出现时从forEach中保释(注意你仍然在每个项目上调用function,它会立即返回)。 You can break out of a forEach but its not idiomatic, you'd have to throw an exception and you try..catch, a bit nasty in JS and not really the intended use for the syntax.可以摆脱 forEach 但它不是惯用的,您必须抛出异常然后尝试..catch,这在 JS 中有点讨厌,并不是语法的真正预期用途。

pc.onicecandidate = function(ice){ 
  if(!ice || !ice.candidate || !ice.candidate.candidate)  return;

  const line = ice.candidate.candidate.split('\r\n').find(function (line) {   
    if (line.indexOf("candidate")!==-1) {           
      var parts = line.split(' ');
      var type = parts[7];
      return type === 'host'
    }
  });
  pc.onicecandidate = noop;
  return line.split(' ')[4]
};

Something like this I think should work for.find.我认为这样的东西应该适用于.find。 .find will return the item, which you can then pull the addr from. .find 将返回该项目,然后您可以从中提取地址。 Alternatively you could let addr outside, update that inside, then ignore the return value from.find.或者,您可以let addr在外面,在里面更新,然后忽略 from.find 的返回值。 Oh, you'll want to add something if your.find returns nothing, or things will break when you try to split it and pull something out.哦,如果 your.find 什么都不返回,你会想要添加一些东西,或者当你尝试拆分它并拉出一些东西时,事情会中断。

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

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