728x90
반응형
728x90
반응형
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="index.js"></script>
</head>
<body>
    <input type="text" id="user" value="koreait">
    <div class="welcome box">Hello world</div>
    <ul id="users">
        <li id="1" data-user-id="1234">홍길동</li>
        <li id="2" data-user-id="5678">김나나</li>
    </ul>
    



    <script>
        const userInput = document.getElementById('user');
        // 속성값 취득
        const userInputVal = userInput.getAttribute('value')
        console.log(userInputVal);
        // 속성값 변경
        userInput.setAttribute('value', 'webstudy');
        // 속성값 존재 확인
        console.log('id 속성 존재? >>',userInput.hasAttribute('id'));
        // 속성값 삭제
        userInput.removeAttribute('value');


        userInput.value = 'test';
        console.log(userInput.value);
        console.log(userInput.attributes);
        console.log(userInput.attributes.id.value);
        console.log(userInput.attributes.type.value);
        // console.log(userInput.attributes.value.value);
        for(let attr of userInput.attributes){
            console.log(attr);
        }

        const users = [...document.getElementById('users').children];
        users.forEach( user => {
            console.log(user.dataset.userId);
        });
        const user5678 = users.find( user => { return user.dataset.userId === '5678'});
        console.log(user5678);

        document.getElementsByTagName('li').item(0).style.color = 'red';
        document.getElementsByTagName('li').item(0).style.backgroundColor = 'black';
        document.getElementsByTagName('li').item(0).style.lineHeight = '3';
        document.getElementsByTagName('li').item(0).style['line-height'] = '1';
        document.getElementsByTagName('li').item(0).style['height'] = '100px';
        console.log(document.getElementsByTagName('li').item(0).style.color);



        const box = document.querySelector('div');
        console.log(box.className);
        box.className = box.className.replace('welcome', 'hello');
        box.classList.add('welcome');
        box.classList.remove('box');
        box.classList.replace('welcome','come');
        box.classList.toggle('box',true); // 있으면 삭제 / 없으면 생성(true/false 가능)
        box.classList.contains('come');



        console.log(box.classList);







    </script>
</body>
</html>
300x250
const aTag = document.getElementsByTagName('a').item(0);
// 복제된 a 태그에 class 속성을 부여한다.
aTag.classList.add('site');
// a태크를 넣을 부모요소 div를 가져온다.
const container = document.getElementById('container');
for(let i = 1; i <= 5; i++){
        // a 태그 노드를 복제한다.
        const aTagClone = aTag.cloneNode();
        // 복제된 a 태그의  href 속성 내가 원하는 걸로 변경한다.
        aTagClone.setAttribute('href','https://search.naver.com/search.naver?where=nexearch&query=test'+i)
        // 복제된 a 태그의 내부 텍스트를 변경한다.
        aTagClone.textContent = 'test'+i;
        //  홀수번째 복제테그에는 color와 text-dacoration style을 추가한다.
        if(i % 2 !== 0){
                aTagClone.style.color = 'rgb(255,0,0)';
                aTagClone.style.textDecoration = 'none';
        }
        // div의 자식으로서 추가한다.
        container.appendChild(aTagClone);
}
// div container의 마지막 자식 요소에 font-size스타일 설정
container.lastElementChild.style.fontSize = '30px';
// h1테그를 생성한다
const h1Tag = document.createElement('h1');
// h1 태그의 텍스트를 변경한다
h1Tag.textContent = '이동링크 페이지1';
// 부모 div태그의 가장 첫 a 태그 전 위치에 h1 태그를 삽입한다.
container.insertBefore(h1Tag, aTag);
container.insertAdjacentHTML('afterbegin','<h1>이동링크 페이지2</h1>');














반응형
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
            background-color: beige;
        }
        .box{
            width: 100px;
            height: 200px;
            background-color: chocolate;
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <div class="box">BOX</div>
    <script>
        const box = document.querySelector('.box');
        // style 프로퍼티는 인라인 스타일만 반환...
        // box.style.backgroundColor = 'red';
        // ComputedStyle은 요소 노드에 적용되어있는 모든 스타일을 종합해서 가져옴
        // 링크스타일, 인라인, JS에 설정한 몯느 스타일이 적용되어진 최종 스타일
        const computedBox = window.getComputedStyle(box);
        let background = computedBox.backgroundColor;
        // rgb(?, ?, ?)
        // setInterval(() => {
            let strtIndex = background.indexOf('(');
            background = background.substring(strtIndex + 1 , background.length -1);
            background = background.split(',');
            let r = background[0].trim();
            let g = background[1].trim();
            let b = background[2].trim();
            box.style.backgroundColor = `rgb(${r}, ${g}, ${10 + b})`;

        // });
        // box.style.backgroundColor = background;
        // box.style.width = '500px';
        // console.log(computedBox.widows);
        // console.log(computedBox.backgroundColor);
        // console.log(computedBox.border);
        // console.log(computedBox.height);

    </script>
</body>
</html>
728x90
반응형

'코딩일지 > WEB' 카테고리의 다른 글

addEventListener 활용2  (0) 2023.01.03
addEventListener 활용1  (0) 2023.01.03
js 기초5  (0) 2023.01.01
js 정규식 연습1  (0) 2023.01.01
js 정규식  (2) 2023.01.01
728x90
반응형
"use strict"


"use strict"
function a(){
    console.log(a);

}

console.log(a);



// async, defer도 아닌 script태그 : 동기적. HTML문서에서 순서대로 차례대로 실행
//          JS파일 다운로드가 끝나면 순서대로 실행함
// async : 비동기적, script 태그 순서와 상관없이 로딩이 완료된 JS부터 실행됨
//      순서가 보장되지 않음. DOM요소와 상관없거나, 최대한 빨리 실행해야하는 JS파일에 설정
// defer : 비동기적, async와 같이 다운로드는 비동기적으로 진행하지만, DOM요소가 전부 로딩이 끝나면 실행
//      DOM요소를 제어해야하는 JS파일에 설정
// 1) 문서 노드(dovument node) : DOM 트리의 최상위에 존재하는 ROOT노드. document 객체를 가리킴
// 2) 요소 노드(element node) :
// 3) 속성 노드(attribute node) : HTML 요소의 속성(어트리뷰트)를 가리키는 객체
// 4) 텍스트 노드(text node) : HTML 요소의 텍스트를 가리키는 객체 (요소 노드의 자식노드)
// Node의 상속 관계
// OBJECT - Event - Node - (Document, Element, Attr, CharacterData)
// Document - HTMLDocument
// Element - HTMLElement - ~~~
// CharacterData - (Text, Comment)


// const element = document.getElementById('banana');
// console.log(element);
// element.style.color = 'blue';





// 스프레드 문법
// const elements = document.getElementsByTagName('li');
// let a, b, c = [...elements].forEach

// Array.from(elements).forEach(el => {
//     el.style.fontSize = '400px';
// });
// for(let el of elements){
//     el.style.fontSize = '400px';
// }
// for(let i = 0; i < elements.length; i++){
//     elements.item(i).style.fontSize = '400px';
// }

// elements.item(0).style.color = 'red';
// console.log('li들 : ', elements);
// console.log('li의 첫번째요소 : ', elements.item(0));

// [...document.getElementsByClassName('fruit2')].forEach(el => {
//     el.style.color = 'green';
// });

// const select = document.querySelectorAll('body > ul li');
// select.forEach(x => {
//     x.style.color = 'green';
// });





const apple = document.querySelector('.apple');
console.log(apple.matches('#fruit > li.apple'));
console.log(apple.matches('#fruit > li.banana'));


// 공백노드 포함. 텍스트 노드 포함해서 가져옴
const fruits = document.getElementById('fruit');
console.log('childNodes 자식들 >> ');
console.log(fruits.childNodes);
// 요소만 가져옴.  텍스트 노드 포함하지 않음
console.log('children 자식들 >> ');
console.log(fruits.children);

// firstChild: childNodes 의 첫번째 노드를 가져옴. 따라서 테그슽노드 포함
console.log('firstChild 자식들 >> ');
console.log(fruits.firstChild);

// firstElementChild: children 첫번째 노드를 가져옴. 따라서 텍스트 노드 포함안함
console.log('firstElementChild 자식들 >> ');
console.log(fruits.firstElementChild);

// 부모 노드 탐색

let lies = document.getElementsByTagName('li');
[...lies].forEach(li => {
    console.log('현재노드>> ', li);
    console.log('parentNode >> ', li.parentNode);
    console.log('parentElement >> ', li.parentElement);
});

console.log("형제 노드 탐색 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
// 형제 노드 탐색
let lies1 = document.getElementsByTagName('li');
[...lies1].forEach(li => {
    console.log('현재노드>> ', li);
    console.log('nextSibling >> ', li.nextSibling);
    console.log('nextElementSibling >> ', li.nextElementSibling);
    li.textContent = '안녕하세요.';
    console.log('현재 li태그의 텍스트: ', li.textContent);
});










// 크로스 사이트 스크립팅 공격(XSS)에 취약함...
// HTML 새니티제이션: XSS 공격 방어 DOMPurify 라이브러리 사용
// DOMPurify.sanitize(<script>alert("You hacked!")</script>)
// const welcome = document.getElementById('welcome');
// [...welcome.getElementsByTagName('span')].forEach(span => {
//     span.style.color = 'blue';
// });
// // welcome.textContent = '<span>test</span>';
// welcome.innerText = '<span>test</span>';
// welcome.innerHTML = '<script>alert("You hacked!")</script>';
// console.log(welcome.textContent); // Node에 존재하는 텍스트 부분
// console.log(welcome.innerText); // 요소에 존재하는 텍스트 부분
// console.log(welcome.innerHTML); // 노드 내부 HTML으로 작성된 텍스트

let fruit = document.getElementById('fruit');
fruit.innerHTML += '<li class="melon">Melon</li>';
document.getElementsByClassName('melon').item(0).style.color = 'green';

fruit.insertAdjacentHTML('afterbegin','<p>afterbegin</p>');
fruit.insertAdjacentHTML('beforebegin','<p>beforebegin</p>');
fruit.insertAdjacentHTML('afterend','<p>afterend</p>');
fruit.insertAdjacentHTML('beforeend','<p>beforeend</p>');

let newNode = document.createTextNode('새로 생성한 텍스트 노드');
fruit.appendChild(newNode);

fruit.replaceChild(newNode, fruit.firstElementChild);

// let welcome = document.getElementById('welcome');
// for(element of fruit.childNodes){
//     welcome.appendChild(element.childNode(true));
// }











728x90
반응형

'코딩일지 > WEB' 카테고리의 다른 글

addEventListener 활용1  (0) 2023.01.03
js 기초6  (0) 2023.01.03
js 정규식 연습1  (0) 2023.01.01
js 정규식  (2) 2023.01.01
js 연습2  (0) 2023.01.01
728x90
반응형
//정규식 연습입니다..
//https://school.programmers.co.kr/learn/courses/30/lessons/72410
// 1단계 new_id의 모든 대문자를 대응되는 소문자로 치환합니다.
// 2단계 new_id에서 알파벳 소문자, 숫자, 빼기(-), 밑줄(_), 마침표(.)를 제외한 모든 문자를 제거합니다.
// 3단계 new_id에서 마침표(.)가 2번 이상 연속된 부분을 하나의 마침표(.)로 치환합니다.
// 4단계 new_id에서 마침표(.)가 처음이나 끝에 위치한다면 제거합니다.
// 5단계 new_id가 빈 문자열이라면, new_id에 "a"를 대입합니다.
// 6단계 new_id의 길이가 16자 이상이면, new_id의 첫 15개의 문자를 제외한 나머지 문자들을 모두 제거합니다.
//      만약 제거 후 마침표(.)가 new_id의 끝에 위치한다면 끝에 위치한 마침표(.) 문자를 제거합니다.
// 7단계 new_id의 길이가 2자 이하라면, new_id의 마지막 문자를 new_id의 길이가 3이 될 때까지 반복해서 끝에 붙입니다.
// 최종적으로 바꾼 아이디를 반환하세요

function kakao(s){
    s = s.toLowerCase(); // 1단계
    s = s.replace(/[^a-z0-9-_.]/g,''); //2단계
    s = s.replace(/\.{2,}/g, '\.'); //3단계
    s = s.replace(/^\.|\.$/g,''); //4단계
    s = s.length === 0 ? 'a' : s; //5단계
    s = s.length >= 16 ? s.substring(0, 15) : s; //6단계
    s = s.replace(/\.$/g, ''); //6단계
    s = s.length <= 2 ? s + s.slice(-1).repeat(3 - s.length) : s; //7단계
    console.log(s)
    return s;
}
console.log( kakao("...!@BaT#*..y.abcdefghijklm") == "bat.y.abcdefghi");
console.log( kakao("z-+.^.") == "z--" );
console.log( kakao("=.=") == "aaa" );
console.log( kakao("123_.def") == "123_.def" );
console.log( kakao("abcdefghijklmn.p") == "abcdefghijklmn" );
728x90
반응형

'코딩일지 > WEB' 카테고리의 다른 글

js 기초6  (0) 2023.01.03
js 기초5  (0) 2023.01.01
js 정규식  (2) 2023.01.01
js 연습2  (0) 2023.01.01
js 기초4  (2) 2023.01.01
728x90
반응형
// 정규식(Regular Expression) : 일정한 패턴을 가진 문자열의 집합을 표현하기 위해 사용하는 형식
// 문자열 내에서 정규식에 맞는 패턴을 검색
// 정규식 플래그(flag) : i, g, m
// i : Ignore case -> 대소문자 구별없이 패턴 검색
// g : Global -> 대상 문자열에서 패턴과 일치하는 모든 문자열을 검색
// m : Multi line -> 문자열의 행이 바뀌더라도 패턴 검색을 계속함
// {숫자1, 숫자2} -> 최소 '숫자1'번 최대 '숫자2' 반복하는 문자열 ('숫자2' 생략시, 최소 '숫자1' 번 이상을 의미) /m{1,}/g 
// ? -> 앞의 패턴이 최대 한번 이상(0번 포함) 반복되는 문자열 
// 패턴1 | 패턴2 -> OR패턴. 패턴1에 해당하던지, 패턴2에 해당하던지. /m{1,}|la/g 
// [문자여러개] -> 범위검색. 해당 문자들에 해당하는 문자열을 찾음 /[sthi]/g, /[a-zA-Z]/g, /[0-9]/g, /[가-힣]/g, /[a-zA-Z0-9]/g 
// [^문자여러개] -> not 검색. 해당 문자에 해당하지 않는 것을 찾음 /[^a-zA-Z0-9]/g
// ^ -> []밖에 있을떄는 문자열의 시작을 의미. /^Is/g(Is로 시작하는가?)
// $ -> 문자열의 마지막을 의미함. 해당 문자 뒤에 쓸 것 \?$/g(?로 끝나는가?)
// 예제1) https:// 로 시작하거나, http:// 로 시작하는지 검사
let message = 'https://www.naver.com'; 
let regexp = /^https?:\/\//g
let result = regexp.test(message); 
// let result = regexp.test(message); // 찾았으면 true, 못찾았으면 false
// result = regexp.exec(message); // 찾은 문자열을 배열로 반환
// let result = message.match(regexp); // 문자열에서 정규식에 해당하는 부분을 배열로 반환
console.log(result);


// 예제2) 아이디가 적합한지 검사를 하자
// 알파벳 대소문자 또는 숫자로 시작하고, 끝나면서 5~10자리인가?
let id = 'test1234';
// /^[a-zA-Z0-9]$/ :알바벳 대소문자 또는 숫자로 시작하고 끝남
// {5,10} : 최소 5개 최대 10개
regexp = /^[a-zA-Z0-9]{5,10}$/g
result = regexp.test(id);
console.log(result);

// 예제3) 매일 주소 형식에 맞는지 검사를 해보자.
let mailAddress = 'test@naver.com';
regexp = /^[0-9a-zA-Z]*@[0-9a-zA-Z]*\.[a-zA-Z]{2,3}$/



let test = 'abcdefgabcdefg';
result = test.replace(/c/g,'');
console.log(result);


// Map은 jey 가 중복이 될 수 없다.
// value는 중복이 되어도 상관없음.
let map = new Map([[500, 10000], ['key2', 'value2']]);
map.set('key3', 'value3');
map.set('key3', 10000);
// map.delete('key2'); // 특정삭제
// map.clear();// 모두삭제
console.log('map : ', map);
map.forEach((v, k, map) =>{
    console.log('현재key : ', k);
    console.log('현재value : ', v);
});

for(let entry of map){
    console.log(entry)
}

console.log([...map]);

for(let k of map.keys()){
    console.log('key => ', k);
};
for(let v of map.values()){
    console.log('value => ', v);
};
for(let entry of map.entries()){
    console.log('enrty => ', entry);
};





let set = new Set([1, 2, 3, 4, 1, 2, 3, 4]);
let set2 = new Set('programming');
set.size
set.add(5);
set.add(4);
console.log(set);
console.log(set2);

set.forEach((v1, v2, set) => {
    console.log('v1: ', v1);
    console.log('v2: ', v2);
});

for(let x of set){
    console.log(x);
}






728x90
반응형

'코딩일지 > WEB' 카테고리의 다른 글

js 기초5  (0) 2023.01.01
js 정규식 연습1  (0) 2023.01.01
js 연습2  (0) 2023.01.01
js 기초4  (2) 2023.01.01
js 연습1  (0) 2023.01.01
728x90
반응형
// 2016 년 1월 1일은 금요일입니다.
// 2016년 a월 b일은 무슨 요일일까요?
// 가능한 a, b를 함수에 전달했을 때,
// 2016년 a월 b일이 무슨 요일인지 리턴하는 함수 '요일탐색'을 완성하세요.
// 요
// 요일의 이름은 일요일부터 토요일까지 각각 "SUM", "MON", "TUE", "WED", "THU", "FRI", "SAT"
// 예를 들어 a = 5, b = 24 라면 5월 24일은 화요일이므로 문자열 'tue'를 반환 후 출력

function 요일탐색(a, b){
let week = ["SUM", "MON", "TUE", "WED", "THU", "FRI", "SAT"]
let date = new Date();
    date.setFullYear(2016, a-1, b);
    return week[date.getDay()];
}
console.log(요일탐색(5,24))


// 2번(https://school.programmers.co.kr/learn/courses/30/lessons/12903): 가운데 글자 가져오기
// 단어 s의 가운데 글자를 반환하는 함수, '중간문자열'을 만들어 보세요.
// 단어의 길이가 짝수라면 가운데 두글자를 반환하면 됩니다. 그리고 결과 출력하세요
// 함수를 호출할 때, 자신이 문자열을 바꿔가면서 테스트해봅니다.
// 예) 중간문자열("test") -> "es" 반환, 중간문자열("fat") -> "a" 반환

let 중간문자열 = (text) => {
    let arr = '';
    const len = text.length;
    if((((len)/2) % 2) == 0){
        arr += text[(len/2)-1];
        arr += text[(len/2)];
    }
    else if((((len)/2) % 2) != 0){
        arr += text[((len-1)/2)];
    }
    return console.log(arr);
}
중간문자열('test');


let s = 'fat';
let 중간문자열2 = (s) => {
    const len = s.length;
    return len % 2 === 0 ? s[len / 2 - 1] + s[len/2] : s[parseInt(len / 2)];
}
console.log(중간문자열2('fat'));



// 3번(https://school.programmers.co.kr/learn/courses/30/lessons/12935): 제일 작은 수 제거하기
// 정수를 저장한 배열, arr 에서 가장 작은 수를 제거한 배열을 리턴하는 함수, '작은수제거'을 완성해주세요. 
// 단, 리턴하려는 배열이 빈 배열인 경우엔 배열에 -1을 채워 리턴하세요. 그리고 결과 출력하세요
// 예를들어 arr이 [4,3,2,1]인 경우는 [4,3,2]를 리턴 하고, [10]면 [-1]을 리턴 합니다.
// 함수를 호출할 때, 자신이 전달하는 배열을 바꿔가면서 테스트해봅니다.
// 예) 작은수제거([1, 2, 3, 4]) -> [2, 3, 4] 반환, 작은수제거([5, 7, 3, 1, 5]) ->  [5, 7, 3, 5] 반환
// 예) 작은수제거([1]) -> [-1] 반환

let 작은수제거 = (...arr) => {
    arr.sort()
    arr.shift();
    console.log(arr[1] >= 1 ? arr : [-1]);
}
작은수제거(1, 2, 3, 4);


let arr = [5, 7, 3, 1, 5];
let 작은수제거2 = (arr) => {
    let min = arr[0];
    for (let i = 0; i < arr.length; i++) {
        if(arr[i] < min){
            min = arr[i];
        }
    }
    let newArr = [];
    for(let i=0; i < arr.length; i++){
        if(arr[i] !== min){
            newArr.push(arr[i])
        }
    }
    return newArr;
}
작은수제거2(arr);



// 4번 (https://school.programmers.co.kr/learn/courses/30/lessons/12916): 문자열 내 p와 y의 개수
// 대문자와 소문자가 섞여있는 문자열 s가 주어집니다. 
// s에 'p'의 개수와 'y'의 개수를 비교해 같으면 True, 다르면 False를 return 하는 '문자찾기' 함수를 완성하세요. 
// 'p', 'y' 모두 하나도 없는 경우는 항상 True를 리턴합니다. 단, 개수를 비교할 때 대문자와 소문자는 구별하지 않습니다.
// 예를 들어 s가 "pPoooyY"면 true를 return하고 "Pyy"라면 false를 return합니다. 그리고 결과를 출력하세요.

let PY = "pPoooyY";
s = PY.toLowerCase();
let 문자찾기 = (Str) => {
    let y1 = 0;
    let p1 = 0;
    for(let value of Str ){
        if(value == 'y'){
            y1++;
        }
        else if(value == 'p'){
            p1++;
        }   
    }
    return y1 == p1 ? true : false;
}
console.log(문자찾기(s));


let 문자찾기2 = (s1) => {
    s1 = s1.toUpperCase();
    let pCount = 0;
    let yCount = 0;
    for (let i = 0; i < s.length; i++) {
        if(s1[i] === 'P'){
            pCount++;
        }
        else if(s1[i] ==='Y'){
            yCount++;
        }
    }
    return pCount === yCount;
}
console.log(문자찾기2('pPoooyY'));

let s5 = 'pPoooyY';
s5.match(/p/ig).length === s5.match(/y/ig).length;




// 반복문
// while > 조건식이 true라면, {}내의 명령을 순서대로 실행
let a = 0;
while(a < 10){
    console.log('test');
    a++;
}


//for - 조건식이 true일 떄 {}안에 있는 명령을 순선대로 실행
for(let i = 0; i < 10; i++){
    console.log('test2');
}






728x90
반응형

'코딩일지 > WEB' 카테고리의 다른 글

js 정규식 연습1  (0) 2023.01.01
js 정규식  (2) 2023.01.01
js 기초4  (2) 2023.01.01
js 연습1  (0) 2023.01.01
js 기초 3  (2) 2023.01.01
728x90
반응형
// Data 객체
let date = new Date();
date.setFullYear(1999, 5, 24);
console.log(date);
console.log(date.toLocaleString());
console.log('현재 요일: ', date.getDay()) 
console.log('현재 일: ', date.getDate()) 
console.log('현재 월: ', date.getMonth())  // 0부터 시작
console.log('현재 연: ', date.getFullYear())  

// String 객체
let s = "This is String";
let s1 = new String("This is String"); // 마지막 순번 : 13, 문자의 개수 : 14
console.log(s.length);
console.log(s.charAt(8));
console.log(s.indexOf("is")); // is 문자열이 s 문자열에서 어디 위치?
console.log(s.includes("String")); // "String"문자열이 s안에 있는가?(숫자 넣으면 거기서 부터 찾아줌)
console.log(s.startsWith("This")); // s 가 "This" 문자열로 시작하는가?
console.log(s.endsWith("?")); // s가 "?" 로 끝나는가?
console.log(s.concat('test')); // s는 바뀌지않고 뒤에 test 연결해줌
console.log(s.replace('is','a')); // s에서 "is" 를 찾아 'a'로 변경
console.log(s.split('is')); //s에서 'is'를 찾아서 나눠 각 요소를 가지고 배열로 만들어준다
console.log(s.slice(0, 7)); // s에서 0번쨰 index부터 7번째 -1 index 까지 잘라서 가져옴
console.log(s.toLowerCase());// s문자열 전체를 소문자로 변경
console.log(s.toUpperCase()) // s문자열 전체를 대문자로 변경
let s2 = '               \t\t test \t\t           ';
console.log(s2.trim()); // 공백제거
console.log(s2.trimStart()); //앞에만 삭제
console.log(s2.trimEnd()); // 뒤에만 삭제
console.log()

// 배열(Array)
let arr = [1, 'true', true, "test", 5];
let arr2 = new Array(5);
console.log(typeof arr[3]); //typeof 타입을 알려줌
console.log(arr.length)
console.log(arr2.length)

arr.push(15);
console.log(arr);
arr2.push(5)
console.log(arr2);

let result = arr.pop(); //배열의 마지막 요소를 제거하고 가져온다
console.log(result);
console.log(arr);
result = arr.shift(); // 맨 처음 요소를 제거하고 가져온다 
console.log(arr);
console.log(result);
arr.unshift(100); // arr 배열의 맨 첫번째 요소로 값을 넣음
console.log(arr)

let newArray = new Array(3);
newArray[0] = 100;
newArray.push(5);
console.log(newArray);

for (let index = 0; index < newArray.length; index++) {
    newArray[index] = index * 10;
    
}
console.log(newArray);

newArray.reverse(); //역순
newArray.sort(); //오름 차순 정렬

// join : 구분자를 각 요소 사이에 넣어서 하나의 문자열로 만들어 줌
result = ['This', 'language', 'is', 'awesome'].join('_');
// slice : 배열을 원하는 길이만큼 잘라서 반환받음
let r = newArray.slice(1, 3); // 1번 index부터 2번 index까지 잘라서 가져옴
console.log(r);
console.log(result);
console.log(newArray);




















 

 

 

 

 

let arr = []; //빈 배열
for (let index = 0; index < 15; index++) {
    arr[index] = parseInt(Math.random() * 100);
    console.log(arr[index]);
}

for(let index in arr){// index 를 순서대로 가져옴
    console.log(index);
}
for(let value of arr){ // 값을 순서대로 가져옴
    console.log(value);

}
console.log('Foreach Start!')
arr.forEach(process);

console.log('Foreach Start!')
arr.forEach(number => {
    console.log(number + 10);
});

function process(number){
    console.log(number);
}

let result = arr.every(number => {
    if(number < 1000){
        return true;
    }
    return false;
});
console.log(result)

console.log('\n\n\n\nfilter! >>>')
result = arr.filter(x => x % 2 == 0).forEach(x => console.log(x));
console.log(result);


console.log('\n\n\n\nmap! >>>')
arr.map( x => {
    if(x < 10){
        return x / 100;
    }
    return x;
}).forEach(x => console.log(x));


let iter = arr.keys();
console.log(iter.next().value);
console.log(iter.next().value);
console.log(iter.next().value);
console.log(iter.next().value);
console.log(iter.next().value);




function a(z, ...x){
    console.log(z);
    console.log(x);
}
a(1, 2, 3, 4, 5, 6, 7);

































728x90
반응형

'코딩일지 > WEB' 카테고리의 다른 글

js 정규식  (2) 2023.01.01
js 연습2  (0) 2023.01.01
js 연습1  (0) 2023.01.01
js 기초 3  (2) 2023.01.01
js 기초2  (0) 2023.01.01
728x90
반응형
// 1번 - 10부터 300까지 숫자 중 6의 배수만 전부 더해서 반환하는 함수를 만드세요 divisor 라는 이름의 함수를 생성하세요. 그리고 결과를 출력하세요.

let divisor = (a, b) => {
    let num = 0;
    for (; a <= b; a++) {
        if((a%6) === 0){  
            num += a;
        }
    }
    return num;
};
console.log(divisor(10,300));



// 2번 - 숫자 두개를 인자로 받아, 두 숫자의 최대 공약수와 최소 공배수를 반환하는 gcd_N_lcm 이라는 함수를 반환하세요. 반환할 떄, 문자열로 반환 "(최대공약수 최소공배수)" 의 형태로 반환하세요. 예) 숫자1 : 2, 숫자2: 6, 반환값: (2, 6)
// 최대공약수 : 두 숫자의 약수 중, 제일 큰 수
// 최소공배수 : 두 숫자의 배수 중, 제일 작은 수


function gcd_N_1cm(num1, num2){
    // 삼항연산자
    // 조건식 ? 참 : 거짓
    let min = num1 < num2 ? num1 : num2;
    for(let i = min; min >= i; i++){
        if(num1 % i === 0 && num2 % i === 0){
            return `(${i}, ${num1 * num2 / i})`;
        } 
    }
}
let result = gcd_N_1cm(6,8);
console.log(result);

function 최대공약수알고리즘(숫자1, 숫자2){
    if(숫자1 % 숫자2 === 0){
        return 숫자2; //최대 공약수
    }
    return 최대공약수알고리즘(숫자2, 숫자1 % 숫자2);
}
console.log(최대공약수알고리즘(1112, 695));




// 재귀함수 : 함수 안에서 자기 자신 함수를 호출하는 것

function recursive(number){
    if(number >= 10){
        return;
    }
    console.log('재귀실행', number)
    recursive(number + 1);
}
recursive(1);

function factorial(number){
    if(number ===1){
        return 1;
    }
    return number * factorial(number - 1);
}
console.log(factorial(3));








728x90
반응형

'코딩일지 > WEB' 카테고리의 다른 글

js 연습2  (0) 2023.01.01
js 기초4  (2) 2023.01.01
js 기초 3  (2) 2023.01.01
js 기초2  (0) 2023.01.01
js 기초  (0) 2023.01.01
728x90
반응형
// 함수의 호출
func1();

//1. 함수 선언문
function func1() {
    console.log('this is func1');
}

// 2. 함수 리터럴

let func2 = function() {
    console.log('this is func2');
}
func2();

// 3. funtion 생성자로 정의(객체 생성자를 호출: new 키워드 사용)
let func3 = new Function('a, b, c',`
    console.log("this is func3"); 
    console.log("test")`
);
func3(15);

// 4.화살표 함수 => 다른 언어의 람다식과 비슷함
let func4 = () => {
    console.log('this is func4');
};
func4();


// 5. 즉시 실행 함수
let func5 = function(){
    console.log('this is func5');
}();
// 일회용 함수
(function(){
    console.log('this is func5');
})();


// 인수 : 함수에 전달하는 값
// 매개변수 : 전달받은 값을 저장하는 변수
// 반환값 : 함수 실행이 종료될 때 돌려주는 값(함수 자체의 값)


let arrow = (a, b, c, d) => {
    console.log(a, b, c, d);
    return true;
}
console.log(arrow(1, 2, 10, 100));


// 생략가능예시1
let arrow1 = a => true;
console.log(arrow1(1));
// 생략가능예시2
let arrow2 = a => console.log(a);
console.log(arrow2(100));


let person = {
    '이름':'김성우',
    '주소':'대구 동구',
    'run': function(){ // 프로퍼티가 함수의 이름이 된다.
        console.log('달리기를 시도합니다.')
    }
};
person.run();





let a = 'b'; // 전역변수
print_info(person);
function print_info(객체){
    let a = 'a'; // 지역변수
    console.log(객체.이름);
    console.log(객체.주소)
    console.log('함수안:', a);
}
console.log('함수밖:', a);



let func = function(x){
    test = 'test'; // let, var, const 안쓰면 전역변수가됨
    console.log(x); 
}
func(3);
console.log(test);


function testFunc(a, b, c, d){
    if(a ===3){
        return true;
    }
    return false;

    console.log(a);
    return 100;
    console.log('test');
}
let result = testFunc(15);
console.log(`result : ${result}`);



// 중첩 함수 : 함수 내부에 함수가 존재하는 함수
// 중첩 함수의 내부함수는 중첩함수 내부에서만 호출 가능( 외부 함수의 기능을 톱는 역할)
function outerFunc(){
    let x = 1;
    function innerFunc(){
        let y = 2;
        console.log('내부함수는 : ', x+y);
    }
    return innerFunc;
}
let r = outerFunc();
r();

// 콜백 함수 : 함수를 인자로 받아, 함수내부에서 인자로 받은 다른 함수를 실행시키는 함수
function testFunc2(함수명){
    함수명();
}
function 인자함수(a, b, c){
    console.log('인자함수가 실행되었습니다.');
}
testFunc2(인자함수);

console.log(인자함수.name);
console.log(인자함수.length);
console.log(인자함수.prototype);

function say(인삿말, 직급){
    console.log(인삿말 + ' ' + this.name + 직급);
}
let 강사 = { name : '김성우'};
say('안녕하세요', 강사,'강사님')
say.apply(강사, ['하이', '강사님!']);
say.call(강사, '하이', '강사님!');
let newFunction = say.bind(강사)
newFunction('하이', '강사님!');


function TEST(){
    this.a = 'A';
    this.b = 'B';
    this.inner = function(){
        console.log('inner');
    }
    console.log(`test: ${this.a}, ${this.b}`)
}
let t = new TEST();
console.log(t.a)
console.log(t.b)
t.inner();















728x90
반응형

'코딩일지 > WEB' 카테고리의 다른 글

js 기초4  (2) 2023.01.01
js 연습1  (0) 2023.01.01
js 기초2  (0) 2023.01.01
js 기초  (0) 2023.01.01
요소 정렬 방법  (0) 2023.01.01

+ Recent posts

728x90
반응형
">