TIL 21.09.28 Javascript

서재환·2021년 9월 28일
0

TIL

목록 보기
25/37

✏️ String

문자접근

let str = "hello, world";

console.log(charAt(1)); // e
console.log(charCodeAt(1)); // 101
console.log(str[1]); // e

문자열 검색 / 변환

string.indexOf(substr, opt)
let text = "hello, world!!!";

console.log(text.indexOf("l")); // 2
console.log(text.indexOf("l", 4)); // 4번째부터 찾아서 index 반환해라 => 10
string,lastIndexOf(substr, opt)
let text = "hello, world!!!";
console.log(text.lastIndexOf("l")); // 뒤에서부터 알파벳을 찾아 인덱스 반환 => 10
string.startsWith(substr)
let text = "hello, world!!!";
console.log(text.startsWith("ello")); => false
console.log(text.startsWith("ello", 1)); => true
string.endsWith(substr)
let text = "hello, world!!!";
console.log(text.endsWith("!!!")); => true
console.log(text.endsWith("d!!")); => false
string.includes(substr)
let text = "hello, world!!!";
console.log(text.includes("hello")); => true
console.log(text.includes("Hello")); => false
string.toUpperCase()
let text = "Hello World";
console.log(text.toUpperCase()); // HELLO WORLD
string.toLowerCase()
let text = "Hello World";
console.log(text.toLowerCase()); // hello world
string.replace(origin_str, change_str)
let text = "Hello, world!"

let changed_text = "";

changed_text = text.replace("world", "earth");
console.log(changed_text); // Hello earth

console.log(changed_text.replace("l", "i")); // Heilo earth
console.log(changed_text.replace(/l/g, "i")); // Heiio earth
console.log(changed_text.replace(/h/gi, "h")); // hello earth

문자열추출

위치 기반 문자열 추출
String.slice(start, end)
let text = "hello world!!!";

console.log(text.slice(0,5)); // hello
console.log(text.slice(0, 1)); // h
console.log(text.slice(0)); // hello world!!!
console.log(text.slice(-3)); // !!!
길이 기반 문자열 추출
String.substring(start, end)
substring() method의 경우 인자가 end > start일 경우 
내부적으로 (start, end) 순으로 바꾸어 입력하게 한다.

substring(end, start) => substring(start, end)

let text = "hello world!!!";

console.log(text.substring(0, 7)); // hello w
console.log(text.substring(7, 0)); // hello w

substr(start, delta) method의 경우 시작 index로 부터 delta 거리까지의 문자열을 출력한다.

console.log(text.substr(1, 4)); // ello
console.log(text.substr(-4, 4)); // d!!!

문자열 분할

배열로 문자열 분할
String.split(Seperator, limit)
let fruits = "apple banana melon";

result = fruits.split(" ");
console.log(result); // ['apple', 'banana', 'melon']

let text = "hello";

console.log(text.split("")); // ['h','e','l','l','o']
console.log(text.split("", 3)); // ['h', 'e', 'l']

✏️ Array

자바스크립트에서의 배열은 Hash 기반의 객체

메모리가 연속적인 밀집배열이 아닌 비 연속적인 희소배열이다.
let arr_1 = new Array(10);
let arr_2 = [];

console.log(arr_1); // [<10 empty items>]
console.log(arr_2); // []

let arr_3 = ['a','b','c']
console.log(arr_3.length); // 3

arr_3[1] = 'd'
console.log(arr_3); // ['a','d','c'];
연속 배열이 아닌 해쉬 배열로 되어 있음을 보여주는 예

let arr = []

arr.push(1);
arr.push(2);
console.log(arr.length); // 2

arr['name']='john'
console.log(arr.length); // 2
배열 타입 확인
Array.isArray(value)
let arr = []
let dict = {}

console.log(Array.isArray(arr)); // true
console.log(Array.isArray(dict)); // false
배열 요소 삭제
delete array[index]
let arr = ['a','b','c']

console.log(arr.length)); // 3

delete 사용시 배열의 요소를 삭제해도 배열의 길이가 줄어들지 않는 문제점이 있다.
따라서 다른 방법을 사용해야 한다.

delete arr[0];

console.log(arr.length)); //3

배열 조작

배열 추가 및 삭제 (뒤)
배열 추가
array.push(value);

배열 삭제
array.pop(value);
배열 추가 및 삭제 (앞)
배열 추가
array.unshift(value);

배열 삭제
array.shift(value);
Array.splice()
let arr = [1, 2, 3];

let res = arr.splice(2); 
console.log(res); // [3]
console.log(arr); // [1, 2]

arr = [1, 2, 3, 4, 5]
let res = arr.splice(0, 3);
console.log(res); // [ 1, 2, 3 ]
console.log(arr); // [4, 5]

arr = [1, 2, 3, 4, 5]
let res = arr.splice(0, 3, 'new');
console.log(res); // [ 1, 2, 3 ]
console.log(arr); // ['new', 4, 5]
Array.slice()
let arr = ['a', 'b', 'c'];

console.log(arr.slice(1)); // ['b', 'c']
console.log(arr); // ['a', 'b', 'c']

console.log(arr.slice(1, 3)); // ['b', 'c']
console.log(arr); //['a', 'b', 'c']
Array.concat()
Array.concat() 은 원본데이터를 건들지 않는다.

let arr = ['a','b','c','d','e'];

console.log(arr.concat(['f','g'])); // ['a','b','c','d','e', 'f', 'g']

console.log(arr); // ['a','b','c','d','e'];
for of Array
let arr = [1, 2, 3];
for(let elem of arr) {
  console.log(elem); // 1, 2, 3
}
for in Array
let arr = ['a', 'b', 'c'];

for(let elem in arr) {
  console.log(elem); // 0, 1, 2
}
배열탐색
indexOf
indexOf(arg1, arg2) arg1은 찾고자하는 값 arg2는 찾기 시작하는 배열의 index이다.
찾고자 하는 값이 배열 내에 없을 때 '-1'을 반환한다.

let arr = [6, 7, 7, 6, 7]
console.log(arr.indexOf(7)); // 1
console.log(arr.indexOf(6, 3)); // 3
console.log(arr.indexOf('apple')); // -1
lastIndexOf
첫번째 인자는 찾는 값을 나타낸다 두번째 인자는 어디서 부터 찾을지 index를 지정해준다.
lastIndexOf(arg1, arg2)는 arg2 index를 기점으로 앞으로 찾고자 하는 값을 찾는다.

console.log(arr.lastIndexOf(8, 2)); // -1
console.log(arr.lastIndexOf(6, 0)); // 0
console.log(arr.lastIndexOf(100, 0)); // -1
배열변형
let arr = [1, -1, 2, -2, 3, -3];

오름차순 정렬
console.log(arr.sort()); //[-3, -2, -1, 1, 2, 3]

내림차순 정렬
console.log(arr.reverse()); //[3, 2, 1, -1, -2, -3]
Array.join();
let arr = ['a','b','c','d','e']

let arr_1 = arr.join()); // a,b,c,d,e
let arr_2 = arr.join(';'); // a;b;c;d;e

let arr_3 = arr_1.split(','); // ['a','b','c','d','e']

고차함수

하나 이상의 함수를 매개변수로 취하거나 함수를 결과로 반환하는 함수

매개변수로 전달되는 함수는 콜백함수(Callback function)
sort() 문제점과 한계점
일의 자리 4가 10의 자리보다 뒤쪽에 정렬, 정렬시 string 으로 바꿔서 정렬하기 때문

대소문자 구문없이 정렬하고 싶을 때에도, 대소문자 구분이되어 정렬된다.

위의 한계점을 극복하기 위해서 고차함수를 사용한다.

sort()함수의 경우 인자로 들어가는 함수의 두 매개변수의 차이가 양수일 경우 배열의 원소에 해당
하는 매개변수가 그 순서를 바꾸고 음수일 경우 배열의 원소에 해당하는 두 매개변수로 들어가는 배
열의 원소가 그 순서를 유지한다.
sort()의 문제점 극복
let arr = [1, -1, 4, 0, 10, 20, 12]

let ascending = function(x, y) {
  return x - y;
}

let descending = function(x, y) {
  return y - x;
}

console.log(arr.sort(ascending)); // [ -1, 0, 1, 4, 10, 12, 20 ]
console.log(arr.sort(descending)); // [ 20, 12, 10, 4, 1, 0, -1 ]
sort()의 한계점 극복
let arr = ["apple", "Orange", "orange", "melon"];

let ascending = function(x, y) {
  x = x.toUpperCase();
  y = y.toUpperCase();
  
  if (x > y) return 1;
  else if (x < y) return -1;
  else return 0;
};

let descending = function(x, y) {
  x = x.toUpperCase();
  y = y.toUpperCase();
  
  if (x > y) return -1;
  else if (x < y) return 1;
  else return 0;
};

console.log(arr.sort(ascending)); // [ 'apple', 'melon', 'Orange', 'orange' ]
console.log(arr.sort(descending));// [ 'Orange', 'orange', 'melon', 'apple' ]
sort()의 문제점과 한계점을 동시에 극복
let ascending = function(x, y) {
  if (typeof x === "string") x = x.toUpperCase();
  if (typeof y === "string") y = y.toUpperCase();
  return x > y ? 1 : -1

let descending = function(x, y) {
  if (typeof x === "string") x = x.toUpperCase();
  if (typeof y === "string") y = y.toUpperCase();
  return x > y ? -1 : 1

✏️ 그 외 고차함수

forEach

배열 요소 별로 콜백 함수에 들어가서 실행

Array..forEach(function(item, index, array){})

let nums = [1, 2, 3]

for(var i = 0; i < nums.length; i++) {
  console.log(nums[i]);
}

nums.forEach(a,b,c) {
  console.log(a); // 1, 2, 3
}

nums.forEach(a,b,c) {
  console.log(b); // 0, 1, 2
}

nums.forEach(a,b,c) {
  console.log(c); // [1, 2, 3] [1, 2, 3] [1, 2, 3]
});

map

배열 요소 별 함수호출 및 결과를 배열로 반환

Array.map(function(item, index, array){})

item: 배열 요소
index: 배열 위치
array: 배열

let nums = [1, 2, 3, 4, 5];
let res = [];

for(var i = 0; i < nums.length; i++) {
  res.push(nums[i]*2);
}
console.log(res); // [2, 4, 6, 8, 10]

let use_map = nums.map(function(item) {
  return item *= 2
})

console.log(use_map); // [2, 4, 6, 8, 10]

find

콜백 함수의 조건을 만족하는, 단 하나의 값만 반환

Array.find(function(item, index, array){})
item: 배열요소
index: 배열위치
array: 배열

let users = [
  { name: 'john', age: 19, job: false },
  { name: 'alice', age: 20, job: false},
  { name: 'javascript', age: 27, job: true}
]

let user_1 = users.find(function(user) {
  return user.job == false; // { name: 'john', age: 19, job: false }
});

let user_2 = users.find(function(user) {
  return user.age > 19; // { name: 'alice', age: 20, job: false},
});

만약 찾는 값이 없으면 undefined를 반환한다.

filter

콜백 함수의 조건을 만족하는 모든 객체를 반환한다.

Array.filter(function(item, index, array){})
item: 배열요소
index: 배열위치
array: 배열

let users = [
  { name: 'john', age: 19, job: false },
  { name: 'alice', age: 20, job: false},
  { name: 'javascript', age: 27, job: true}
]

let user_1 = users.filter(function(user) {
  return user.job == false; // { name: 'john', age: 19, job: false }
}); // [ { name: 'john', age: 19, job: false },{ name: 'alice', age: 20, job: false } ]

let user_2 = users.filter(function(user) {
  return user.age > 19; // { name: 'alice', age: 20, job: false},
}); // [ { name: 'alice', age: 20, job: false },{ name: 'javascript', age: 27, job: true } ]

reduce

요소 별 함수 수행 누적 결과값 반환
initial이 없다면 index 1부터 시작

Array.reduce(function(accumulator, item, index, array){})
accumulator: 이전 함수 결과(initial로 초기값 설정가능) default = 0;

accumulator를 설정하지 않을 경우 0번째 index 스킵하고 첫번째 원소를 함수값으로 가짐

item: 배열요소,
index: 배열위치,
array: 배열

let nums = [1, 2, 3, 4, 5];
let cnt = 0;
console.log('accumulator\t', 'item\t', 'index\t');
let sum = nums.reduce(function(accumulator, item, index){
  console.log(accumulator, "\t\t", item, "\t\t", index);
  cnt++;
  return accumulator + item;
}, 0);

console.log(cnt);  // 4
console.log(sum);

/*
accumulator      item            index
0                1               0
1                2               1
3                3               2
6                4               3
10               5               4

15(accumulator + item)
*/

✏️ 생성자

유사한 객체를 다중으로 만들 때 사용되는 함수 (타 언어에서의 class 개념과 유사)

일반적으로 생성자 함수의 첫 글자는 대문자로 시작

생성자 함수로 객체 생성 시 new 연산자를 통해 객체 생성
function FishBread(flavor, price) {
  this.flavor = flavor; 
  this.price = price ;
  this.base = "flour";
}

let bread_1 = new FishBread("cream", 1200);
let bread_2 = new FishBread("redbean", 1000);
let bread_3 = new FishBread("strawberry", 1500);

console.log(bread_1);

0개의 댓글