欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
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];
 
}
 
例子解释
 
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。
 
索引顺序依赖于实现,可能不会按照您期望的顺序访问数组值。
 
当顺序很重要时,最好使用 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;
 
}
 
请注意,该函数采用 3 个参数:
 
项目值
 
项目索引
 
数组本身
 
上面的例子仅使用 value 参数。可以改写为:
 
实例
 
const numbers = [45, 4, 9, 16, 25];
 
let txt = "";
 
numbers.forEach(myFunction);
 
function myFunction(value) {
 
  txt += value;
 
}

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h64423.shtml