1. keypress 이벤트

  • onkeydown(KeyCode) : 사용자가 키보드의 키를 눌렀을 때
  • onkeyup(KeyCode) : 사용자가 키보드의 키를 눌렀다가 뗐을 때
  • onkeypress(ASCII) : 사용자가 키보드의 키를 눌렀을 때

* onkeydown과 onkeypress의 차이

  • onKeyPress는 ASCII 값으로 사용되서 shift, ctrl 같은 키는 인식하지 못함.
  • keydown과 keyup이벤트는 모든 문자를 인식하는 반면, keypress는 한글을 인식하지 않음.

2. indexOf()

string.indexOf(searchvalue, position)

  • indexOf 함수는, 문자열(string)에서 특정 문자열(searchvalue)을 찾고, 검색된 문자열이 ‘첫번째’로 나타나는 위치 index를 리턴함.
  • searchvalue : 필수 입력값, 찾을 문자열
    position : optional, 기본값은 0, string에서 searchvalue를 찾기 시작할 위치
  • 찾는 문자열이 없으면 -1을 리턴
  • 문자열을 찾을 때 대소문자를 구분함

3. hasOwnProperty()

obj.hasOwnProperty(prop) :
객체가 특정 프로퍼티를 가지고 있는지를 나타내는 boolean 값을 반환함.

1
2
3
4
const object1 = {};
object1.property1 = 42;

console.log(object1.hasOwnProperty('property1')); //true

4. $.grep()

배열의 모든 항목을 받아 콜백 함수에 의해 필터 함수를 만족하는 배열을 반환시키는 함수

1) 사용 방법

$.grep( Array, function ( value, index ){ }, [, invert] );

  • Array : 검색할 배열 객체(유형: ArrayLikeObject)
  • function : 각 항목을 처리하는 기능
    (유형 : Function(Object elementOfArray, Integer indexInArray)Boolean 반환)
    함수의 첫 번째 인수는 항목이고 두 번째 인수는 인덱스임
  • invert : invertfalse이거나 제공되지 않은 경우 함수는 콜백이 true를 반환하는 모든 요소로 구성된 배열을 반환함
    invert가 참이면 함수는 콜백이 거짓을 반환하는 모든 요소로 구성된 배열을 반환함
    (유형: Boolean)

2) 예제

1
2
3
4
5
6
7
var array = [1,2,3,4,5,6,7,8,9]; 
var newArray = $.grep(array, function(value, index) { 
		   return value % 2 == 0; 
		}); 
console.log("결과:" + newArray.join(", "));

//결과: 2, 4, 6, 8 

5. Number()

  • 문자열이나 다른 값을 Number 타입으로 변환.
  • 만약 인수를 숫자로 변환할 수 없으면 NaN을 리턴.
1
2
3
4
5
Number('123'); // 숫자 123을 반환
Number('123') === 123; // 참

Number('unicorn'); // NaN
Number(undefined); // NaN

6. String.fromCharCode()

  • String.fromCharCode(num1[, ...[, numN]])
  • 매개변수 num1, ..., numN :
    • UTF-16 코드 유닛인 숫자 뭉치.
    • 가능한 값의 범위는 0부터 65535(0xFFFF)까지.
    • 0xFFFF를 초과하는 값은 잘림.
    • 유효성 검사는 하지 않음.
1
2
3
String.fromCharCode(65, 66, 67);  // "ABC"
String.fromCharCode(0x2014)       // "—"
String.fromCharCode(0x12014)      // 숫자 '1'은 무시해서 "—"

7. Node.textContent / Document.createTextNode() + Node.appendChild()

1) Node.textContent

1
<div id="divA">This is <span>some</span> text!</div>
1
2
3
4
5
6
7
8
// 1. 요소의 텍스트 콘텐츠 가져오기
let text = document.getElementById('divA').textContent;
// The text variable is now: 'This is some text!'

// 2. 텍스트 내용을 설정
document.getElementById('divA').textContent = 'This text is different!';
// The HTML for divA is now:
// <div id="divA">This text is different!</div>

2) Document.createTextNode() + Node.appendChild()

1
2
3
<div style="border: 1px solid red">
<p id="p1">단락의 첫번째 줄.<br /></p>
</div>
1
2
3
var newtext = document.createTextNode(" 동적으로 추가되는 텍스트. ");
var para = document.getElementById("p1");
para.appendChild(newtext);

8. Element.append() / Node.appendChild()

  • append 메서드는 appendChild보다 간결하게 요소를 추가할 수 있으며,
    여러 요소를 한 번에 추가할 수 있는 장점이 있음.
  • 하지만 append 메서드는 모든 최신 브라우저에서 지원되는 것은 아니므로, 호환성에 주의해야 함.
    appendChild는 모든 브라우저에서 지원되는 메서드.

1) Element.append()

1
2
3
4
var parent = document.getElementById("parent");
var child1 = document.createElement("div");
var child2 = document.createElement("span");
parent.append(child1, child2);

2) Node.appendChild()

1
2
3
var parent = document.getElementById("parent");
var child = document.createElement("div");
parent.appendChild(child);

8-1. Node.insertBefore()

  • 참조된 노드(referenceNode) 앞에 특정 부모 노드의 자식 노드(newNode)를 삽입.

parentNode.insertBefore(newNode, referenceNode);

  • referenceNode 는 선택 인자가 아님.
    명시적으로 Nodenull을 전달해야 함.
1
2
3
<div id="parentElement">
   <span id="childElement">foo bar</span>
</div>
1
2
3
4
var newNode = document.createElement("span");
var parentDiv = document.getElementById("childElement").parentNode;
var sp2 = document.getElementById("childElement");
parentDiv.insertBefore(newNode, sp2);

연습 문제

1
2
3
4
5
<div id="parent">
    <div>child</div>
    <div>child</div>
    <div>child</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// appendChild() 함수는 두 개의 매개변수 parent와 child를 받습니다.
// parent는 요소의 부모 엘리먼트이며, child는 추가할 요소입니다.
// appendChild() 함수는 parent 요소의 자식 요소들 중에서 가장 앞에 child 요소를 추가합니다.
// appendChild() 함수를 사용하여 요소를 추가하는 동작을 구현하세요.

function appendChild(parent, child) {
  // parent 요소의 가장 앞에 child 요소 추가 구현
  const firstChild = parent.firstChild;
  parent.insertBefore(child, firstChild);
}

// 사용 예시
var parentElement = document.getElementById("parent");
var childElement = document.createElement("div");
childElement.textContent = "New Child";

appendChild(parentElement, childElement);

9. Element.classList

toggle( String [, force] )

  • 하나의 인수만 있을 때:
    클래스가 존재한다면 제거하고 false를 반환하며, 존재하지 않으면 클래스를 추가하고 true를 반환.
  • 두번째 인수가 있을 때:
    두번째 인수가 true로 평가되면 지정한 클래스 값을 추가하고 false로 평가되면 제거.
1
2
3
4
5
6
7
8
9
10
11
12
const div = document.createElement('div');
div.className = 'foo';

// if visible is set remove it, otherwise add it
div.classList.toggle("visible");
// add/remove visible, depending on test conditional, i less than 10
div.classList.toggle("visible", i < 10 );

// add or remove multiple classes using spread syntax
const cls = ["foo", "bar"];
div.classList.add(...cls);
div.classList.remove(...cls);

10. Array.from()

  • Array.from() 메서드는 유사 배열 객체(array-like object)나 반복 가능한 객체(iterable object)를 얕게 복사해 새로운 Array 객체를 만듦.
1
2
3
4
5
6
7
8
9
10
11
12
13
// 1. 문자열 ⇒ 배열
Array.from('foo');  // ["f", "o", "o"]

// 2. 배열 형태를 가진 객체(arguments) ⇒ 배열
function f() {
  return Array.from(arguments);
}
f(1, 2, 3);   // [1, 2, 3]

// 3. 화살표 함수 사용
Array.from([1, 2, 3], x => x + x);    // [2, 4, 6]
// 길이가 5인 빈 배열에 값을 할당
Array.from({length: 5}, (v, i) => i); // [0, 1, 2, 3, 4]

10-1. 매핑 함수(mapping function)

  • 각 요소의 값을 변환하여 새로운 배열을 생성하는 데 사용.
  • 매핑 함수는 세 가지 매개변수를 가질 수 있음.
    1. 현재 요소의 값(value)
    2. 현재 요소의 인덱스(index)
    3. 원본 배열(또는 유사 배열 객체) 자체
  • 매핑 함수는 이 매개변수를 활용하여 각 요소의 값을 원하는 방식으로 변환하고, 그 변환된 값을 새로운 배열의 해당 인덱스에 할당함.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 매핑 함수를 사용하여 배열의 각 요소를 제곱하여 새로운 배열 생성
var arr1 = [1, 2, 3, 4, 5];
var squaredArr = Array.from(arr1, (value) => value * value);
console.log(squaredArr); // [1, 4, 9, 16, 25]

// 매핑 함수를 사용하여 배열의 각 요소를 문자열로 변환하여 새로운 배열 생성
var arr2 = [1, 2, 3];
var stringArr = Array.from(arr2, (value) => String(value));
console.log(stringArr); // ['1', '2', '3']

// 매핑 함수를 사용하여 배열의 각 요소에 인덱스를 더하여 새로운 배열 생성
var arr3 = ['apple', 'banana', 'orange'];
var modifiedArr = Array.from(arr3, (value, index) => value + index);
console.log(modifiedArr); // ['apple0', 'banana1', 'orange2']

연습 문제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 문제: 사용자로부터 양의 정수 n을 입력받아서 1부터 n까지의 각 숫자를 제곱한 값을 가지는 배열을 생성하는 프로그램을 작성하세요.

// 요구사항:
// Array.from() 메서드를 사용하여 입력받은 양의 정수 n까지의 숫자로 이루어진 배열을 생성합니다.
// 매핑 함수를 사용하여 각 숫자를 제곱하여 변환합니다.
// 최종적으로 변환된 값으로 이루어진 배열을 출력합니다.

// Input: 5
// Output: [1, 4, 9, 16, 25]

function answer(n) {
    return Array.from({length: n}, (v, i) => (i+1)**2); // 제곱연산자
}

console.log(answer(5));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 문제: 문자열로 이루어진 배열을 입력받아서 각 문자열의 길이가 홀수인 경우에만 대문자로 변환하여 새로운 배열을 생성하는 프로그램을 작성하세요.

// 요구사항:
// Array.from() 메서드를 사용하여 문자열로 이루어진 배열을 입력받습니다.
// 매핑 함수를 사용하여 각 문자열의 길이가 홀수인 경우에만 대문자로 변환합니다.
// 최종적으로 변환된 문자열로 이루어진 새로운 배열을 출력합니다.
// Input: ["apple", "banana", "kiwi", "orange", "grape"]
// Output: ["APPLE", "GRAPE"]

function answer(arr) {
    // filter(Boolean): false, 0, -0, 0n, "", null, undefined, NaN 제거
    return Array.from(arr, (v, i) => v.length%2 == 0 ? null : v.toUpperCase()).filter(Boolean);
}

const arr = ["apple", "banana", "kiwi", "orange", "grape"];
console.log(answer(arr));

11. Array.prototype.reduce()

  • 콜백 함수의 반환값을 누적하여 최종 결과값을 반환함.
    따라서 reduce() 메서드는 배열을 하나의 값으로 축소(reduce)할 수 있음.
  • 배열을 축소하거나, 배열의 요소들을 결합하거나, 배열에 기반한 다른 데이터 구조를 만드는 등의 작업에 유용함.
    또한, 누적값을 이용하여 복잡한 연산 수행 가능.
  • 콜백 함수에서 반환하는 값에 따라 반복을 중단할 수 있음.
    즉, 콜백 함수에서 조건을 만족하는 경우에 중간에 반복을 중단하고 최종 결과값을 반환할 수 있음.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 총합 계산
var numbers = [1, 2, 3, 4, 5];
var sum = numbers.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);
console.log(sum); // 15

// 배열의 최댓값 찾기
var numbers = [10, 5, 20, 8, 16];
var max = numbers.reduce(function(accumulator, currentValue) {
  return Math.max(accumulator, currentValue);
});
console.log(max); // 20

// 배열의 평균값 계산하기
var numbers = [5, 10, 15, 20];
var average = numbers.reduce(function(accumulator, currentValue, currentIndex, array) {
  accumulator += currentValue;
  if (currentIndex === array.length - 1) {
    return accumulator / array.length;
  }
  return accumulator;
}, 0);
console.log(average); // 12.5