For In 循环
JavaScript for in
语句循环遍历对象的属性:
语法
for (key in object) {
// code block to be executed
}
实例
<!DOCTYPE html>
<html lang="en">
<body>
<P id="demo"></P>
<script>
const person = { fname: "Rose", lname: "Jenny", age: 20 };
let txt = "";
for (let x in person) {
txt += person[x] + "";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
//RoseJenny20
例子解释
- for in 循环遍历 person 对象
- 每次迭代返回一个键 (x)
- 键用于访问键的值
- 键的值为 person[x]
For In 遍历数组
JavaScript for in
语句也可以遍历数组的属性:
语法
for (variable in array) {
code
}
实例
<!DOCTYPE html>
<html>
<body>
<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()
方法为每个数组元素调用一次函数(回调函数)
<!DOCTYPE html>
<html>
<body>
<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 个参数:
- 项目值
- 项目索引
- 数组本身
<!DOCTYPE html>
<html>
<body>
<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>