我是javascript的新手并尝试做一些自动格式化数字的循环(1000 = 1K,10000 = 10k 100000 = 100k)
格式化为1K有效,然后由于某种原因停止...
对我来说,这个循环是有道理的:循环将循环一次,因此条件为真,这将给出前2个整数和' K',之后循环将中断
如果条件不成立,循环应该继续......
这可能不是理想的做法,但我想知道为什么我的逻辑思维是错误的
感谢先生并抱歉我的英语不好。
<body >
<p>Number: <span id="number"></span></p>
<script>
len=1;
thousand=1000;
million =1000000;
num= 10001;
for(thousand;thousand<million;thousand*=10){ //when thousand is less then a million , multiply thousand times 10
if(num>=thousand && num<(thousand*10)){ // should cycle the loop twice so i got num>=10000 && num<100000
document.getElementById("number").innerHTML = num.toString().substring(0,len)+" K";
len+=1; // increase by 1 , so i will get 10 K instead of 1 K
break; // should break now since condition is true after second cycle
}
}
// probaly not the ideal method to do this , i just want to know my problem because this loop makes sense to me....
</script>
</body>
&#13;
答案 0 :(得分:0)
在这种情况下循环是没有意义的,因为你没有迭代的数组类型。 另外产生一个循环范围,就像你要做的那样,不值得,因为你可以
n = Math.floor(n / 1000) + 'k';
请参阅chrisz的回答,了解一个工作号码是否为k&#39;过滤
如果你真的想循环。试试这个:
let n = 3024;
for (let i = 0; i < 1000; i++) {
if (n >= i * 1000 && n < (i + 1) * 1000) {
console.log(i + 'k');
break;
}
}
&#13;