ES6.3 : for ... in / of... iterations

Austin Jiuk Kim·2022년 4월 7일
0

JavaScript

목록 보기
4/6

for iteration are divided into for ... in ... and for ... of ....

  • for ... in ... can access the key.
  • for ... of ... can access the value.

for ... in ...

let arr = [10,20,30,40]

for (let val in arr) {
  console.log(val)
}
0
1
2
3

let obj = {
  a: 1,
  b: 2,
  c: 3,
};

for (let val in obj) {
  console.log(val);
}
a
b
c

With for ... in ..., you can get value using indexing.

let array = [10, 20, 30, 40];

for (let val in array) {
  console.log(array[val]);
}
10
20
30
40

for ... of ...

let array = [10, 20, 30, 40];

for (let val of array) {
  console.log(val);
}
10
20
30
40

let obj = {
  a: 1,
  b: 2,
  c: 3,
};

for (let val of obj) {
  console.log(val);
}
TypeError: obj is not iterable
    at Object.<anonymous> (/Users/basecamp/repo/ES6/es6.js:14:17)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47
profile
그냥 돼지

0개의 댓글