For In
循环JavaScript for in
语句循环访问对象的属性:
for (key in object) {
// code block to be executed
}
const person = {fname:"John", lname:"Doe", age:25};
let text = "";
for (let x in person) {
text += person[x];
}
自己尝试一下 →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For In Loop</h2>
<p>The for in statement loops through the properties of an object:</p>
<p id="demo"></p>
<script>
const person = {fname:"John", lname:"Doe", age:25};
let txt = "";
for (let x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
for in 循环迭代 person 对象
每次迭代都会返回一个键 (x)
键用于访问键的值
键的值为person[x]
For In
数组之上JavaScript for in
语句也可以循环遍历数组的属性:
for (variable in array) {
code
}
const numbers = [45, 4, 9, 16, 25];
let txt = "";
for (let x in numbers) {
txt += numbers[x];
}
自己尝试一下→
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>For In Loops</h2>
<p>The for in statement can loops over array values:</p>
<p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
let txt = "";
for (let x in numbers) {
txt += numbers[x] + "<br>";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
如果索引顺序很重要,请勿在数组上使用for in。
索引顺序取决于实现,并且可能不会按照您期望的顺序访问数组值。
当顺序很重要时,最好使用 for 循环、for of 循环或 Array.forEach()。
Array.forEach()
forEach()
方法为每个数组元素调用一次函数(回调函数)。
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value, index, array) {
txt += value;
}
自己尝试一下→
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The forEach() Method</h2>
<p>Call a function once for each array element:</p>
<p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;
function myFunction(value, index, array) {
txt += value + "<br>";
}
</script>
</body>
</html>
请注意,该函数有 3 个参数:
物品价值
项目索引
数组本身
上面的示例仅使用 value 参数。可以将其重写为:
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value) {
txt += value;
}
自己尝试一下→
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The forEach() Method</h2>
<p>Call a function once for each array element:</p>
<p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;
function myFunction(value) {
txt += value + "<br>";
}
</script>
</body>
</html>