For In
ciklusA JavaScript for in
utasítás egy objektum tulajdonságain keresztül fut át:
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];
}
Próbálja ki Ön is →
<!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>
A for in ciklus egy személy objektum felett iterál
Minden iteráció egy kulcsot ad vissza (x)
A kulcs a kulcs értékének elérésére szolgál
A kulcs értéke person[x]
In
Over ArraysA JavaScript for in
utasítás egy tömb tulajdonságait is áthaladhatja:
for (variable in array) {
code
}
const numbers = [45, 4, 9, 16, 25];
let txt = "";
for (let x in numbers) {
txt += numbers[x];
}
Próbálja ki Ön is →
<!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>
Ne használja a for in értéket egy tömbön keresztül, ha az index sorrendje fontos.
Az index sorrendje megvalósításfüggő, és előfordulhat, hogy a tömbértékek nem a várt sorrendben érhetők el.
Jobb a for ciklus, az for of vagy az Array.forEach() használata, ha a sorrend fontos.
Array.forEach()
A forEach()
metódus minden tömbelemhez egyszer hív meg egy függvényt (egy visszahívási függvényt).
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value, index, array) {
txt += value;
}
Próbálja ki Ön is →
<!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>
Vegye figyelembe, hogy a függvénynek 3 argumentuma van:
A tétel értéke
A cikkindex
Maga a tömb
A fenti példa csak az érték paramétert használja. Átírható erre:
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value) {
txt += value;
}
Próbálja ki Ön is →
<!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>