For In de JavaScript

For In 循环

JavaScript for in 语句循环遍历对象的属性:

语法

for (key in object) {
  // código bloque a ser ejecutado
}

Ejemplo

const person = {fname:"Bill", lname:"Gates", age:25};
let text = "";
for (let x in person) {
  text += person[x];
}

Pruebe usted mismo

例子解释

  • for in 循环遍历 person 对象
  • 每次迭代返回一个 (x)
  • 键用于访问键的
  • 键的值为 person[x]

For In 遍历数组

JavaScript for in 语句也可以遍历数组的属性:

语法

for (variable in array) {
  code
}

Ejemplo

const numbers = [45, 4, 9, 16, 25];
let txt = "";
for (let x in numbers) {
  txt += numbers[x];
}

Pruebe usted mismo

Si el índiceSecuenciaMuy importante, no utilice for in

La secuencia de índices depende de la implementación y puede no acceder a los valores del arreglo en el orden esperado.

Es mejor usar cuando la secuencia es importante for Ciclo,for of Ciclo o Array.forEach()

Array.forEach()

forEach() El método llama a la función una vez para cada elemento del arreglo (función de retroalimentación).

Ejemplo

const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value, index, array) {
  txt += value;
}

Pruebe usted mismo

Tenga en cuenta que esta función toma 3 parámetros:

  • Valor del elemento
  • Índice del elemento
  • Arreglo en sí mismo

El ejemplo anterior solo utiliza el parámetro value. Puede rewritten como:

Ejemplo

const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value) {
  txt += value;
}

Pruebe usted mismo