split

문자열을 일정한 구분자로 잘라서 배열로 저장하기 위해서는 split() 함수를 사용한다.
새로운 문자 배열을 반환

const str = "abc";

const arr = str.split("");

console.log(arr[0]); //a
console.log(arr[1]); //b
console.log(arr[2]); //c
const str = "apple,banana,orange";

const arr = str.split(",", 2);

document.writeln(arr.length); // 2
document.writeln(arr[0]); // apple
document.writeln(arr[1]); // banana
document.writeln(arr[2]); // undefined
const str = "apple,banana,orange";

const arr = str.split(",");

document.writeln(arr.length); // 3
document.writeln(arr[0]); // apple
document.writeln(arr[1]); // banana
document.writeln(arr[2]); // orange

join

join() 메서드는 배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.
split랑 반대

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

console.log(elements.join(''));
// expected output: "FireAirWater"

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"

repeat

repeat() 메서드는 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환함.

var str = "Hi";

console.log(str.repeat(0)); // 
console.log(str.repeat(1)); //hi
console.log(str.repeat(2)); //hihi
console.log(str.repeat(3)); //hihihi
'abc'.repeat(-1);   // RangeError (반복횟수는 양의 정수여야함.)
'abc'.repeat(0);    // ''
'abc'.repeat(1);    // 'abc'
'abc'.repeat(2);    // 'abcabc'
'abc'.repeat(3.5);  // 'abcabcabc' (소수점 뒷자리는 버려짐)

substring

substring() 메소드는 string 객체의 시작 인덱스로 부터 종료 인덱스 전 까지 문자열의 부분 문자열을 반환합니다.

const str = 'Mozilla';

console.log(str.substring(1, 3));
// expected output: "oz"

console.log(str.substring(2));
// expected output: "zilla"

substr은 legacy 함수로 간주되므로 가능하면 피해야 한다. 핵심 JavaScript 언어의 일부가 아니며 향후 제거될 수 있음. 가능하면 substring() 메서드를 사용 할 것.

silce

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]

Math.min

Math.min() 함수는 주어진 숫자들 중 가장 작은 값을 반환

아래 수식은 x 와y 중 작은 값을 찾아 z 에 할당 합니다.

var x = 10, y = -20;
var z = Math.min(x, y);

Math.max

Math.max()함수는 입력값으로 받은 0개 이상의 숫자 중 가장 큰 숫자를 반환한다.

console.log(Math.max(1, 3, 2));
// expected output: 3

console.log(Math.max(-1, -3, -2));
// expected output: -1

const array1 = [1, 3, 2];

console.log(Math.max(...array1));
// expected output: 3

math.sqrt

math.sqrt()제곱근을 구해주는 math메소드

parseInt, Number

문자열을 정수로 바꿔주는 함수
"1234" -> 1234

String, toString

숫자를 문자열로 바꿔주는 함수
String(),객체.toString();

toString에는 진법 변환 기능도 있다.

var value = 10;
// 10진법 -> 2, 8, 16 진법으로 변환
value.toString(2);    // 1010
value.toString(8);    // 12
value.toString(16);   // a
var bin = 1010,
    oct = 12,
    hex = 'a';
// 2, 8, 16 진법 -> 10진법으로 변환
Number.parseInt(bin, 2);    // 10
Number.parseInt(oct, 8);    // 10
Number.parseInt(hex, 16);   // 10

Number.isInteger

Number.isInteger() : 정수인지 아닌지 체크하는 방법
정수면 true, 아니면 false를 출력함

reduce

reduce() 메서드는 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환함.

    <script>
        a=[10,11,12,13,14,15];
        let answer=a.reduce(function(acc,i){
            return acc+i;
        }, 0);
        console.log(answer);
    </script>

결과값
75

여기서 acc는 0이야.
전처럼 10을 의미하는게 아님.
return 0 + 10
retrun 10 + 11
21 + 12..........이렇게 쭉 가는거임.

return값이 acc로 감

누산기 (acc)
현재 값 (cur)
현재 인덱스 (idx)
원본 배열 (src)

리듀서 함수의 반환 값은 누산기에 할당되고, 누산기는 순회 중 유지되므로 결국 최종 결과는 하나의 값이 됩니다.

const array1 = [1, 2, 3, 4];
const reducer = (previousValue, currentValue) => previousValue + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

forEach

: 호출하는거. for문 대신 사용하는거

function forEach(predicate, thisArg) : 첫번째는 함수. 콜백함수 내부에서 this로 사용할애를 전달받는다.
두개의 인자를 받아야한다. thisArg는 생략 할 수 있음 함수는 꼭 넘겨야됨

첫번째는 값이고 두번째는 인덱스
함수를 안에 인자로 콜백함수로 만들어야한다.

            a=[10,11,12,13,14,15];
            a.forEach(function(v, i){
                console.log(v, i);
            });

결과값

10 0
11 1
12 2
13 3
14 4
15 5

            a=[10,11,12,13,14,15];
            a.forEach(function(v, i){
                console.log(v, i, this);
            }, [1,2]);

결과값

map

요소를 하나하나 탐색해서 새로운 배열을 생성하는것

            a=[10,11,12,13,14,15];
            let answer=a.map(function(v,i){
                return v*v;
            });
            console.log(answer);

결과값

짝수만 저장해보기

            a=[10,11,12,13,14,15];
            let answer=a.map(function(v,i){
                if(v%2==0) return v;
            });
            console.log(answer);

근데 이렇게하면 짝수값만 저장되는것같지? ㄴㄴ
원래 배열과 길이는 동일해.

결과값

map은 원본 배열 요소들을 이용해서 새로운 배열을 생성 그 새로운 배열은 원본배열과 길이가 같다.

https://7942yongdae.tistory.com/48 [프로그래머 YD]

filter

새로운 배열을 생성해서 리턴받는데
리턴함수가 참을 리턴한 그 요소만 새로운 배열에 생성함
원본 배열 요소들을 추출.

        a=[10,11,12,13,14,15];
        let answer=a.filter(function(v,i){
            return v%2==0;
        });
        console.log(answer);

결과값

map, filter, reduce 차이점

map은 원본 배열을 이용하여 새로운 배열을 생성하는 것이 용도인데 꼭 원본과 같은 길이의 배열을 생성한다.

filter는 원본 배열의 원소를 통해서 새로운 배열의 원소를 추출하되 길이는 다를 수 있다.

reduce는 배열의 원소들로 함수를 작동시키며 값을 계속 누적하는 기능을 한다.

화살표 함수

let sum = (a, b) => a + b;

/* 위 화살표 함수는 아래 함수의 축약 버전입니다.

let sum = function(a, b) {
  return a + b;
};
*/

alert( sum(1, 2) ); // 3
let sum = (a, b) => {  // 중괄호는 본문 여러 줄로 구성되어 있음을 알려줍니다.
  let result = a + b;
  return result; // 중괄호를 사용했다면, return 지시자로 결괏값을 반환해주어야 합니다.
};

alert( sum(1, 2) ); // 3

자주쓰이는 정규표현식

https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=jeongju02&logNo=221517177533

test

test() 메서드는 주어진 문자열이 정규 표현식을 만족하는지 판별하고, 그 여부를 true 또는 false로 반환함.

sort

sort() 메서드는 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다. 정렬은 stable sort가 아닐 수 있습니다. 기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따릅니다.

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

sort를 이용한 오름차순, 내림차순

const numbers = [15, 52, 23, 11, 9]; 

// 오름차순 정렬, 원본 배열 수정
numbers.sort((a, b) => a - b); 
console.log(numbers); // [9, 11, 15, 23, 52] 

// 내림차순 정렬, 원본 배열이 다시 수정 
numbers.sort((a, b) => b - a); 
console.log(numbers); // [52, 23, 15, 11, 9]

indexOf

문자 위치 찾아주기

keskkset

s.indexOf('k');
결과 : 0
풀이 : 0번 인덱스에 k가 있음

s.indexOf('k', 1);
결과 : 3
풀이 : 1번 인덱스 이후, 3번인덱스에 k가 있음

만약, 발견못하면 결과값은 -1임

profile
♪(๑ᴖ◡ᴖ๑)♪ 기회는 도전에서부터 시작되는 것

0개의 댓글