02.JavaScript-Array, Loops

이수현·2022년 4월 27일
0

TIL

목록 보기
2/23

📚JavaScript 개념정리

배열이 필요한 이유와 선언하는 방법

  • 배열(Array)를 사용하면 일정한 규칙이 있거나, 연관이 있는 데이터들을 관리하는 것이 편리하다.
  • 또한, 여러 데이터를 관련성 있게 관리할 수 있기 때문에 생산성 및 코드 가독성이 높아지고 이는 유지보수 비용의 감소로 이어진다
  • 자바스크립트는 명시적 타입이 없기 때문에, 하나의 배열은 여러 자료형을 가질 수 있는 특징이 있다.
// 배열을 선언하는 방법
// 첫번째
const fruits = ['Apple', 'Banana'];
// 두번째
const fruits = new Array(2);
fruits.push('Apple');
fruits.push('Banana');
// 세번째
const fruits = 'Apple,Banana'.split(',');
// 네번째
const fruits = new Array('Apple','Banana');

배열의 값을 추가, 수정, 삭제하는 방법

배열에 요소를 추가하는 방법

  • push(...arg) - push() 메서드를 이용해 추가하면 arg가 배열의 마지막에 추가된다.
  • unshift(...arg) - unshift() 메서드를 이용해 추가하면 arg가 배열의 처음에 추가된다.
  • concat(...arg) - concat() 메서드를 이용하면 arg가 배열의 마지막에 추가된다.
  • splice(start,0,...arg) - splice() 메서드를 이용하면 arg가 배열의 인덱스가 start인 곳에 추가된다.
// push()
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count); // 추가된 후 배열의 새 길이를 return한다.
console.log(animals); // ["pigs", "goats", "sheep", "cows"]
animals.push('chickens', 'cats', 'dogs');
console.log(animals); // ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

// unshift()
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5)); // 추가된 후 배열의 새 길이를 return한다.
console.log(array1); // [4, 5, 1, 2, 3]

// concat()
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3); // ["a", "b", "c", "d", "e", "f"]

// splice()
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
console.log(months); // ["Jan", "Feb", "March", "April", "June"]

배열의 요소를 수정하는 방법

  • indexOf()splice(start,end,...arg)를 이용한 방법
  • map을 이용한 방법
let fruits = ["apple", "banana", "grape", "mango", "orange"];
let index = fruits.indexOf("banana");
fruits.splice(index, 1, "lemon");
console.log(fruits); // [ 'apple', 'lemon', 'grape', 'mango', 'orange' ]

let fruits = ["apple", "banana", "grape", "mango", "orange"];
fruits[1] = 'lemon';
console.log(fruits); // [ 'apple', 'lemon', 'grape', 'mango', 'orange' ]

let fruits = ["apple", "banana", "grape", "mango", "orange"];
const newFruits = fruits.map((item) => {
  if (item === "banana") {
    return "lemon";
  }
  return item;
});
console.log(newFruits); // [ 'apple', 'lemon', 'grape', 'mango', 'orange' ]

배열의 요소를 삭제하는 방법

  • indexOf()splice(start,end,...arg)를 이용한 방법
  • pop()을 이용한 방법
  • shift()를 이용한 방법
  • filter를 이용한 방법
  • slice(start, end)를 이용한 방법
  • delete를 이용한 방법
let fruits = ["apple", "banana", "grape", "mango", "orange"];
let index = fruits.indexOf("banana");
fruits.splice(index, 1);
console.log(fruits); // [ 'apple', 'grape', 'mango', 'orange' ]

let fruits = ["apple", "banana", "grape", "mango", "orange"];
const popReturn = fruits.pop();
console.log(popReturn); // 'orange'
console.log(fruits); // [ 'apple', 'banana', 'grape', 'mango' ]

let fruits = ["apple", "banana", "grape", "mango", "orange"];
const shiftReturn = fruits.shift();
console.log(shiftReturn); // 'apple'
console.log(fruits); // [ 'banana', 'grape', 'mango', 'orange' ]

let fruits = ["apple", "banana", "grape", "mango", "orange"];
const newFruits = fruits.filter((item) => item !== "banana");
console.log(newFruits); // [ 'apple', 'grape', 'mango', 'orange' ]

let fruits = ["apple", "banana", "grape", "mango", "orange"];
const newFruits = fruits.slice(0, 4);
console.log(newFruits); // [ 'apple', 'banana', 'grape', 'mango' ]

// delete 키워드는 해당값을 undefined로 변환해준다.(오히려 수정의 기능을 한다고 볼 수 있다.) 
let fruits = ["apple", "banana", "grape", "mango", "orange"];
delete fruits[1];
console.log(fruits); // [ 'apple', <1 empty item>, 'grape', 'mango', 'orange' ]

배열의 5가지 메서드와 사용 방법

  1. filter()
  2. map()
  3. find()
  4. forEach()
  5. flatMap()
  6. entries()
  7. every()
  8. sort()
  9. join()
  10. reduce()
  11. reduceRight()
  12. keys()
  13. some()
/**
* 조건에 맞는 모든 아이템들을 새로운 배열로 반환!
* filter((element, index, array) => { /* ... * / })
* filter(function(element) { /* ... * /}, thisArg)
* filter(callbackFn, thisArg)
*/
let fruits = ["apple", "banana", "grape", "mango", "orange"];
const result = fruits.filter((element) => element.length > 5);
console.log(result); // [ 'banana', 'orange' ]

let fruits = ["apple", "banana", "grape", "mango", "orange"];
const result = fruits.filter(function deleteBanana(element) {
  return element !== "banana";
});
console.log(result); // [ 'apple', 'grape', 'mango', 'orange' ]

function deleteBanana(element) {
  return element !== "banana";
}
let fruits = ["apple", "banana", "grape", "mango", "orange"];
const result = fruits.filter(deleteBanana);
console.log(result); // [ 'apple', 'grape', 'mango', 'orange' ]
/**
* 배열의 아이템들을 각각 다른 아이템으로 매핑할 수 있는, 다른 아이템으로 매핑(변환)해서 새로운 배열 반환!
* map((element, index, array) => { /* ... * / })
* map(function(element) { /* ... * /}, thisArg)
* map(callbackFn, thisArg)
*/
let fruits = ["apple", "banana", "grape", "mango", "orange"];
const result = fruits.map((element) => {
  if (element.length > 5) {
    return "Too Long...";
  }
  return element;
});
console.log(result); // [ 'apple', 'Too Long...', 'grape', 'mango', 'Too Long...' ]

let fruits = ["apple", "banana", "grape", "mango", "orange"];
const result = fruits.map(function nameLength(element) {
  return element.length;
});
console.log(result); // [ 5, 6, 5, 5, 6 ]

function nameLength(element) {
  return element.length;
}
let fruits = ["apple", "banana", "grape", "mango", "orange"];
const result = fruits.map(nameLength);
console.log(result); // [ 5, 6, 5, 5, 6 ]
/**
* 조건(콜백함수)에 맞는 아이템을 찾을 때 제일 먼저 조건에 맞는 아이템을 반환!
* find((element, index, array) => { /* ... * / })
* find(function(element) { /* ... * /}, thisArg)
* find(callbackFn, thisArg)
*/
const item1 = { name: "🍕", price: 2 };
const item2 = { name: "🍜", price: 3 };
const item3 = { name: "🍣", price: 1 };
const item4 = { name: "🍜", price: 9999 };
const products = [item1, item2, item3, item4];
console.log(products);
let result = products.find((value) => {
  return value.name === "🍜";
});
console.log(result); // { name: "🍜", price: 3 }
/**
* 조건(콜백함수)에 맞는 아이템을 찾을 때 제일 먼저 조건에 맞는 아이템을 반환!
* forEach((element, index, array) => { /* ... * / })
* forEach(function(element) { /* ... * /}, thisArg)
* forEach(callbackFn, thisArg)
*/
let fruits = ["apple", "banana", "grape", "mango", "orange"];
fruits.forEach((element, index, array) => {
  if (element !== "banana") {
    array[index] = element;
  } else {
    array[index] = "lemon";
  }
});
console.log(fruits); // [ 'apple', 'lemon', 'grape', 'mango', 'orange' ]
// 언뜻보면 map()과 유사한 것 같지만, forEach()는 return 값이 undefined이다.
// 그래서 값을 변경하려면 위의 코드처럼 배열이 한 번 반복될 때마다 조건문을 통과하게 해서 조건에 부합하면 값을 재할당 하는 방식으로
// 코드를 작성해야 한다.
/**
* 조건(콜백함수)에 맞는 아이템을 찾을 때 제일 먼저 조건에 맞는 아이템을 반환!
* flatMap((element, index, array) => { /* ... * / })
* flatMap(function(element) { /* ... * /}, thisArg)
* flatMap(callbackFn, thisArg)
*/
let fruits = ["apple", "banana", "grape", "mango", "orange"];
const mapResult = fruits.map((item) => [item]);
const flatMapResult = fruits.flatMap((item) => [item]);
console.log(mapResult); // [ [ 'apple' ], [ 'banana' ], [ 'grape' ], [ 'mango' ], [ 'orange' ] ]
console.log(flatMapResult); // [ 'apple', 'banana', 'grape', 'mango', 'orange' ]
// flatMap()은 주어진 콜백함수를 배열의 각 요소에 적용하고 결과를 1단계 level로 병합하여 형성된 새로운 배열을 반환한다! 
// [item] => [ 'apple', 'banana', 'grape', 'mango', 'orange' ]
// [[item]] => [ [ 'apple' ], [ 'banana' ], [ 'grape' ], [ 'mango' ], [ 'orange' ] ]
// map()과 1단계 level의 차이가 있는 것 같다!
/**
* sort()  Functionless
* sort((a, b) => { / * ... * /})
* sort(compareFn)
* sort(function compareFn(a, b) { / * ... * /})
* sort() 메서드는 기본적으로 오름차순으로 정렬되며, 요소를 문자열로 변환한 후 UTF-16 코드 단위 값의 시퀀스를 비교할 때 작성된다.
* 그리고 이것은 구현에 의존하기 때문에 정렬의 시간 및 공간 복잡도는 보장될 수 없다.
* 또한, sort() 메서드는 원본배열을 바로 정렬하고 정렬된 원본배열이 리턴된다.
*/
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1); // [ 1, 100000, 21, 30, 4 ] => 문자열로 변환한 후 비교되므로 이런 결과가 나옴.

// return값이 음수이면 a가 b앞에 위치, 양수이면 a가 b뒤에 위치, 0이면 그대로
// 그 결과, a-b => 오름차순 , b-a => 내림차순이 된다.
const array1 = [1, 30, 4, 21, 100000];
array1.sort((a, b) => a - b); // [ 1, 4, 21, 30, 100000 ] 
console.log(array1);

function asending(a, b) {
  return a - b;
}
const array1 = [1, 30, 4, 21, 100000];
array1.sort(asending);
console.log(array1); // [ 1, 4, 21, 30, 100000 ] 
/**
* reduce((accumulator, currentValue, currentIndex, array) => { / * ... * / }, initialValue)
* reduce(callbackFn, initialValue)
* reduce(function(accumulator, currentValue, currentIndex, array) { / * ... * / }, initialValue)
*/
// reduce() 메서드는 배열의 각 요소에 대해 콜백 함수를 순서대로 실행하고 accumlator에 이전 함수의 결과값을 전달한다.
// 밑의 코드는 이러한 reduce()의 특징을 이용하여, 배열요소의 합을 구하고있다.
const array1 = [1, 2, 3, 4];
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue
);

console.log(sumWithInitial); // 10

반복문이 필요한 이유와 사용하는 방법

  • 반복문이 필요한 이유: 코드를 간결하게 만드는데 도움이 된다.

  • 반복문을 사용하는 방법: 반복문은 반복문의 종류에 따라 조건식이 들어가고 해당 조건이 만족하지 않을 때까지 반복하도록 사용할 수 있다.

반복문의 종류

  • for
    -for([initialExpression]; [conditionExpression]; [incrementExpression]) { statement }
  • do ... while
    -do { statement } while(conditionExpression)
  • while
    -while(conditionExpression) { statement }
  • for ... in
    -for(variable in object) { statement }
  • for ... of
    -for(variable of object) { statement }
// for()
for (let i = 0; i < 5; i++) {
  for (let j = 0; j < 5; j++) {
    console.log(i, j); // (0,0) (0,1) (0,2)... (4,4) 
  }
}

//while()
let num = 5;
while (num >= 0) {
  console.log(num); // 5 4 3 2 1 0
  num--;
}

//for ...in
const obj = { id: 123, name: "lee" };
for (const key in obj) {
  console.log(key); // id, name
}

// for ...of
const arr = [3, 5, 7];
arr.foo = "hello";
console.log(arr); // [ 3, 5, 7, foo: 'hello' ]
for (let i in arr) {
  console.log(i); // "0", "1", "2", "foo"
}

[for ...in]과 [for ...of]차이점

  • for ...in객체의 모든 열거 가능한 속성에 대해 반복한다.
  • for ...of는 [Symbol.iterator] 속성을 가지는 컬렉션 전용이다.

forEach는 Array(배열)을 순회하는 데 사용되는 Array 메서드이고, for ...of는 이터러블 객체를 모두 순회할 수 있는 강력한 반복문이다. 또한 forEach구문과 달리 break, continue, 그리고 return 구문과 함께 사용할 수 있다.

반복문과 함께 사용하는 제어문

  • label - 프로그램 내의 특정 영역을 식별할 수 있도록 해주는 식별자이다.

  • break - 루프 내에서 사용하여 해당 반복문을 완전히 종료시키고, 반복문 바로 다음에 위치한 실행문으로 프로그램의 흐름을 이동시킨다.

  • continue - 루프 내에서 사용하여 해당 루프의 나머지 부분을 건너뛰고, 바로 다음 표현식으로 넘어가게 한다.
// continue
let str = "";

for (let i = 0; i < 5; i++) {
  if (i === 1) {
    continue;
  }
  str = str + i;
}
console.log(str); // 0234

//break
let str = "";

for (let i = 0; i < 5; i++) {
  if (i === 1) {
    break;
  }
  str = str + i;
}

console.log(str); // 0

//label
let i, j;

loop1: for (i = 0; i < 3; i++) {
  loop2: for (j = 0; j < 3; j++) {
    if (i === 1 && j === 1) {
      continue loop1;
    }
    console.log("i = " + i + ", j = " + j); 
  }
}
//i = 0, j = 0
//i = 0, j = 1
//i = 0, j = 2
//i = 1, j = 0
//i = 2, j = 0
//i = 2, j = 1
//i = 2, j = 2

배열과 반복문을 함께 자주 사용하는 이유

  • 반복문은 동일한 코드를 정해진 횟수만큼 반복하는 구문이다. 구문에는 주로 변수 증감을 위한 명령을 많이 사용하는데, 배열의 index가 해당 역할을 수행하기에 적합하기 때문에 함께 자주 사용된다.

  • 그리고 배열은 특정 데이터의 집합인데, 이 데이터들의 집합을 이용해서 특정 조건일 때 특정 결과를 도출해낼 때 용이하기 때문에 함께 자주 사용된다.

참고자료

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
https://www.w3schools.com/js/js_array_methods.asp
https://www.edureka.co/blog/javascript-loops/
https://ko.javascript.info/array-methods
https://www.geeksforgeeks.org/how-to-sort-numeric-array-using-javascript/
https://jsdev.kr/t/for-in-vs-for-of/2938
https://doozi0316.tistory.com/entry/JavaScript-for-in-for-of%EC%9D%98-%EC%B0%A8%EC%9D%B4#:~:text=for...of%20%EB%8A%94%20%EB%B0%B0%EC%97%B4,%EC%9D%98%20%EB%B0%98%EB%B3%B5%EC%97%90%EC%84%9C%20%EC%82%AC%EC%9A%A9%EB%90%9C%EB%8B%A4.
https://n-log.tistory.com/39
http://hacks.mozilla.or.kr/2015/08/es6-in-depth-iterators-and-the-for-of-loop/

0개의 댓글