如何计算for循环中的字长

时间:2016-10-27 06:27:45

标签: javascript loops

我有这样的循环数据:

for (var i = 0; i < 11;i++){
console.log(i); 
}

我的问题如何获得字长,所以我想要得到这样的结果:

0 <-- this length is 1
1 <-- this length is 1
2 <-- this length is 1
3 <-- this length is 1
4 <-- this length is 1
5 <-- this length is 1
6 <-- this length is 1
7 <-- this length is 1
8 <-- this length is 1
9 <-- this length is 1
10 <-- this length is 2

3 个答案:

答案 0 :(得分:4)

您可以使用toString()函数将其解析为字符串,然后获取string的{​​{3}}

&#13;
&#13;
for (var i = 0; i < 11;i++){
  console.log(i + ' <- this length is ' + i.toString().length); 
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这应该可以解决问题:

for(var i = 0; i < 11; i++){
    console.log(i + " <-- this length is " + i.toString().length);
}

答案 2 :(得分:0)

for (var i = 0; i < 11;i++){
    console.log(i + ' <- this length is ' + (i+'').length);
}