JavaScript:for..in循环中的else语句破坏了我的if语句

时间:2016-02-23 07:13:21

标签: javascript if-statement for-in-loop

我在for in循环中有一个if语句可以正常工作,但是当我在结尾处添加else语句时,代码会中断 - 就像在变量中一样(在本例中是键) for..in循环没有传递给else语句。这是代码:

config = {'test1':2, 'test2':2, 'test3':5, 'test4':8}

  for (key in config) {
    if (isNaN(item)) {
      return item;
    }
    if (key.indexOf(baseCcy) !== -1) {
      console.log("match config");
      item = parseFloat(item).toFixed(config[key]);
      return item;
    } else {
      item = parseFloat(item).toFixed(10);
      return item;
    }
  }

baseCcy和item是来自angular的输入,来自以下代码:| {{fill.price | decimalFilter:baseCcy}}这点是创建一个自定义过滤器,我在过滤器内部执行for..in循环来实现它。到目前为止,它运作良好,但其他声明只是打破了它。 else语句的要点是,如果item的输入都不匹配配置数组,则返回10位小数的项。

值得注意的是,当我在for..in循环之后调试.log key时,它只显示我" test1",但当我删除else语句时(只有两个if) ,console.log键显示我" test1"," test2"," test3"," test4"。 '

2 个答案:

答案 0 :(得分:2)

您只能从函数返回!

如果要退出循环结构,请使用$adminRoute = //check if this is admin or frontend url ("/admin/user/1" or "/user/username") if($adminRoute){ $router->bind('user', function ($value) { return app(UserInterface::class)->findOrFail($value); }); }else{ //nothing }

链接到相关的More on BAML

示例:

break

答案 1 :(得分:0)

只需对当前逻辑进行一些更改,这一定对您有用。

config = {'test1':2, 'test2':2, 'test3':5, 'test4':8}
var newItemValue; // a new varialble
  for (key in config) {    
    if (isNaN(item)) {
      newItemValue = item
      break;  //break once you find the match
     //return item;      
    }
    else if (key.indexOf(baseCcy) !== -1) {
      console.log("match config");
      item = parseFloat(item).toFixed(config[key]);
      newItemValue = item
      break;//break once you find the match
      //return item;       
    } 
  }
  //if the loop was a failure, then do this by default.
  if(typeof newItemValue === 'undefined'){  // check if there is no value assigned to the new variable, if its not then the loop was a failure
      item = parseFloat(item).toFixed(10);
      newItemValue = item     
  }

以下是Working JsFiddle

的链接

上述逻辑的输出是(当item = 12.12345678baseCcy ='test3'

12.12346

编辑:在阅读完您的上一条评论后,我认为这就是您想要的。

  config = {'test1':2, 'test2':2, 'test3':5, 'test4':8}

  for (key in config) {
    if (isNaN(item)) {
      return item;
    }
    if (key.indexOf(baseCcy) !== -1) {
      console.log("match config");
      item = parseFloat(item).toFixed(config[key]);
      return item;
    } 
  }
  //if the program has reached this line then the loop was a failure
  item = parseFloat(item).toFixed(10);
  return item;

这里不需要新变量,另外还有其他东西。

相关问题