JavaScript: else 语句在 for.in 循环中破坏了我的 if 语句
JavaScript: else statement inside a for..in loop is breaking my if statement
我在 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.12345678
和baseCcy ='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;
这里不需要新的变量,另一个其他的东西。
相关文章:
- "工具提示"jQuery插件坏了
- 我的按钮坏了
- 节点JS:时间机器坏了——timekeeper.travel不做时间旅行
- HTML/JavaScript:为什么不'我的纽扣坏了
- 为什么下面的if语句排除了一个'It’s和其他的一样
- 我的素数函数坏了,但我没有;我不知道为什么
- Uglifier是不是弄坏了我的睡衣
- if语句禁用了我的jquery函数/按钮
- 什么'这个javascript语句错了
- 我升级了Knockout.js,现在我的模板坏了
- 为什么范围$手表坏了
- 所有的javascript都 ajax.aspnetcdn.com/ajax/ 坏了?打破所有外部引用?自周五以来
- 角度控制器功能坏了
- 谷歌可视化图表API示例坏了,如何修复它们
- 将Facebook应用程序移动到新服务器,现在它坏了
- 嵌套的 if/else 语句讨论了分配变量.我已经这样做了,但它仍然不起作用
- 为什么我的代码坏了
- 野生动物园浏览器中的后退按钮坏了
- 砌体坏了(可能是经典)
- if语句被其他语句卡住了