繁体   English   中英

如何从函数返回一个值?

[英]how to return a value from function?

我需要从我使用 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


    }

  }

}

您可以为此使用辅助变量。 因此,在所有循环之后,您可以发送要返回的值。 但是,请记住,您的函数可以返回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;
}

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

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
    }
  }
}

暂无
暂无

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

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