我在 JavaScript 方面相对较新,我发现了一个奇怪的 for 循环,比如这个:
for (c in "test message") {
}
通常,像这样的东西在foreach循环中,'c'元素应该循环字符(t,e,s,t等......)......这个循环整数......?!
是否有一些文档可以理解这种行为?
完整样本如下:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to loop through the
properties of an object named "person".</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x;
var txt = "";
var person = { fname: "John", lname: "Doe", age: 25 };
var myString = "this is a test";
for (x in myString) {
txt = txt + x + ':' + myString[x] + '<br/>';
}
for (x in person) {
txt = txt + x + ':' + person[x] + '<br/>';
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
输出:
0:t
1:h
2:i
3:s
4:
5:i
6:s
7:
8:a
9:
10:t
11:e
12:s
13:t
fname:John
lname:Doe
age:25