This question already has answers here:
JavaScript Loops: for…in vs for
                            
                                (4个答案)
                            
                    
                3年前关闭。
        

    

为什么我会得到数字(0到9)来尝试打印字符串中的每个字符?字符串的长度是10,所以我能得到每个字母的索引吗?如何获得角色呢?我想获得Python将以类似代码提供的输出(下面的JS和Python代码以及自己的输出)。我在Google Chrome浏览器的控制台上尝试了此操作。代码和输出如下:

strng = 'This is me';
for (var charac in strng)
{
     console.log(charac);
}


输出是

0
1
2
3
4
5
6
7
8
9


同样具有for-in格式的Python将每行打印每个字符。这就是我想要的。以下来自终端iPython的代码和输出:

strng = 'This is me'

for charac in strng:
   print(charac)


Python输出为:

T
h
i
s

i
s

m
e

最佳答案

MDN


  for ... in语句遍历一个对象的可枚举属性
  对象,以任意顺序。对于每个不同的属性,语句可以
  被执行。


尝试使用of语句:

strng = 'This is me';
for (var charac of strng)
{
     console.log(charac);
}

07-24 18:36
查看更多