【问题标题】:how to return a value from function?如何从函数返回值?
【发布时间】:2018-08-17 14:10:28
【问题描述】:

我需要从我使用 2 for 循环和 if 语句的函数中返回一个值

function getTextColor(context) {
  var selection = context.selection;
  for(var i = 0; i < selection.count(); i++){
    var layer = selection[i];
    const attr = layer.CSSAttributes()
    const regex = /#\w{6}/
    for (let i = 0; i < attr.length; i++){
      let color = attr[i].match(regex)
      if (color)
        return color[0]   // I need to return this value from my function


    }

  }

}

【问题讨论】:

  • 那么上面的代码有什么问题?我看到的唯一问题是,如果循环没有找到任何东西,你就不会返回任何东西。
  • 返回颜色[0];这就是您问题的答案。

标签: javascript


【解决方案1】:

您可以为此使用辅助变量。因此,在所有循环之后,您可以发送值以返回。但是,请记住,您的函数可以返回 null 值。

function getTextColor(context) {
  let aux = null;
  const selection = context.selection;
  for (let i = 0; i < selection.count(); i++) {
    const layer = selection[i];
    const attr = layer.CSSAttributes();
    const regex = /#\w{6}/;
    for (let i = 0; i < attr.length; i++) {
      let color = attr[i].match(regex);
      if (color)
        aux = color[0];
    }
  }
  return aux;
}

【讨论】:

  • 所以你在找到它之后继续循环???好像是在浪费 CPU
【解决方案2】:

您可以在初始化变量时简单地调用该函数。在这种情况下,变量颜色将保存您的函数返回的颜色。

var color = getTextColor(context);

function getTextColor(context) {
  var selection = context.selection;
  for(var i = 0; i < selection.count(); i++){
    var layer = selection[i];
    const attr = layer.CSSAttributes()
    const regex = /#\w{6}/
    for (let i = 0; i < attr.length; i++){
      let color = attr[i].match(regex)
      if (color)
        return color[0]   // I need to return this value from my function
    }
  }
}

【讨论】:

  • 不,var color = getTextColor(context); 是您调用函数的方式。您所做的只是getTextColor 不再是可调用函数;相反,它的名字是color。在浏览器控制台中尝试var foo = function bar() { return 2; },然后尝试调用bar()
猜你喜欢
  • 1970-01-01
  • 2016-11-17
  • 2020-03-09
  • 1970-01-01
  • 2019-12-06
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多