The For In Loop
for in statement loops through the properties of an Object:
<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>
John Doe 25
For In Over Arrays
<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>
45
4
9
16
25
Array.forEach()
The forEach() method calls a function (a callback function) once for each array element.
<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>
45
4
9
16
25
The example above uses only the value parameter
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value) {
txt += value;
}
인덱스 순서 가 중요한 경우 배열 에 for in 을 사용하지 마십시오 .
순서가 중요한 경우 for 루프, for of 루프 또는 Array.forEach() 를 사용하는 것이 좋습니다.
For Of
for of statement loops through the values of an iterable object.
<p id="demo"></p>
<script>
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
BMW
Volvo
Mini
<p id="demo"></p>
<script>
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
J
a
v
a
S
c
r
i
p
t
'JavaScript' 카테고리의 다른 글
javaScript - Set (0) | 2022.11.21 |
---|---|
JavaScript - Iterables (0) | 2022.11.21 |
JavaScript - Comparison (0) | 2022.11.17 |
JavaScript - Booleans (0) | 2022.11.17 |
JavaScript - Math Object (0) | 2022.11.17 |