标题: JavaScript For In [打印本页] 作者: vicky.yu 时间: 2023-6-5 09:13 标题: JavaScript For In
For In 循环
JavaScript for in 语句循环遍历对象的属性:
语法
for (key in object) {
// code block to be executed
}
实例
const person = {fname:"Bill", lname:"Gates", age:25};
let text = "";
for (let x in person) {
text += person[x];
}
亲自试一试
例子解释
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];
}
亲自试一试
如果索引顺序很重要,请不要在数组上使用 for in。