관리 메뉴

Silver Library (Archived)

For in, For of 용도 본문

F2. Problem & Solving/Solving

For in, For of 용도

Chesed Kim 2021. 9. 22. 15:45
반응형

For...of

for...of 명령문반복가능한 객체 (Array, Map, Set, String, TypedArray, arguments 객체 등을 포함)에 대해서 반복하고 각 개별 속성값에 대해 실행되는 문이 있는 사용자 정의 반복 후크를 호출하는 루프를 생성합니다.

 

For...in

for...in문은 상속된 열거 가능한 속성들을 포함하여 객체에서 문자열로 키가 지정된 모든 열거 가능한 속성에 대해 반복합니다.

 

여기서 사용이 낯선 것이 for of statement 입니다. 그래서, 이 글은 for of 문에 초점을 둡니다.

const array1 = ['a', 'b', 'c'];

for (const element of array1) {
  console.log(element);
}

// expected output: "a"
// expected output: "b"
// expected output: "c"

요약: array1 의 (배열에 속한) 객체를 element 의 이름으로 반복합니다.

 

여기서 핵심은, for const element of array1 과 array1 입니다.

저렇게 알기 쉬운 단어로 적어두면, 이해하기에도 편리하다고 생각됩니다.


for in 의 경우.

const object = { a: 1, b: 2, c: 3 };

for (const property in object) {
  console.log(`${property}: ${object[property]}`);
}

// expected output:
// "a: 1"
// "b: 2"
// "c: 3"

요약: object 객체에, 포함된 속성 {a: 1, b: 2, c: 3} 을, property 의 (고정)변수로 서 속성을 반복합니다.


여기서 의문이 드는게, '그래서 이건 실제 문제에서 어떻게 적용이 가능한가?' 입니다.

 

function twoNumberSum(array, targetSum) {
	const nums = []; // nums 변수 선언.
    for (const num of array) { // for of 조건문이 쓰였습니다.
      const potentialMatch = targetSum - num; // 조건문 발동을 위한 작업을 합니다.
    	if (potentialMatch in nums) { // 해당 변수가 읽어질 시, nums를 토대로 진행 합니다.
        	return [potentialMatch, num];
    } else {
      nums[num] = true;
	}
  }
return [];
}

exports.twoNumberSum = twoNumberSum;


// array = [3, 5, -4, 8, 11, 1, -1, 6]
// targetSum = 10

// expected output : [-1, 11]

 

그외 참고하면 좋은 링크:

https://jsdev.kr/t/for-in-vs-for-of/2938

 

 

'F2. Problem & Solving > Solving' 카테고리의 다른 글

Algorithm - change of plan (language)  (0) 2021.11.16
Linear & binary search with Python  (0) 2021.11.15
JS - wrapper object  (0) 2021.07.07
JS - switch  (0) 2021.07.06
[Node.js] - what is readline() modul?  (0) 2021.07.06