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

JavaScript: else statement inside a for..in loop is breaking my if statement

本文关键字:语句 坏了 循环 我的 if in else for JavaScript      更新时间:2023-09-26

我在 for in 循环中有一个 if 语句,可以正常工作,但是当我在末尾添加 else 语句时,代码中断 - 就像变量(在本例中为 key )一样,来自 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..在过滤器内部循环以实现它。到目前为止,它运行良好,但 else 语句只是打破了它。else 语句的要点是,如果来自 item 的任何输入都与配置数组不匹配,则返回带有 10 位小数的项目。

值得注意的是,当我安慰时.log key在 for..在循环中,它只显示"test1",但是当我删除 else 语句(只有两个 if)时,控制台.log键显示我"test1"、"test2"、"test3"、"test4"。'

你只能从函数返回!

如果要退出循环结构,请使用 break

链接到相关文档。

例:

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

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

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     
  }

这是工作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;

这里不需要新的变量,另一个其他的东西。