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].
Для входных массивовОператор 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>