728x90

자바스크립트 구조분해할당과 keys를 얻는 방법에 대해 간략하게 적어둔다.

 

 
const user = {
    name:'홍길동',
    age: 25,
    email:'link2me@gmail.com'
}
 
// 구조 분해 할당 : 필요한 변수만 지정할 수 있다.
const { name, age, email } = user;
console.log(`사용자의 이름은 ${name}입니다.`);
console.log(`${name}의 나이는 ${age}세 입니다.`);
console.log(`${name}의 이메일은 ${email}세 입니다.`);
 
/***
 * Object.keys(obj) – 객체의 키만 담은 배열을 반환.
 * Object.values(obj) – 객체의 값만 담은 배열을 반환
 * Object.entries(obj) – [키, 값] 쌍을 담은 배열을 반환
 */
const keys = Object.keys(user);
console.log(keys); // [ 'name', 'age', 'email' ]
 
console.log(user['email']);
 
const values = keys.map(key => user[key])
console.log(values); // [ '홍길동', 25, 'link2me@gmail.com' ]
 
for(let key in user){
    console.log(`${key} ${user[key]}`);
}
 

 

 

 

블로그 이미지

Link2Me

,
728x90

JavaScript의 Object.assign()메서드 사용법을 알아보자.

불변성(immutable)을 지켜야 된다면 Object.assign을 사용하는 것 보다 스프레드 연산자를 사용하는 것이 좋다.
Object.assign으로 불변성을 지키려면 target에 항상 {} 빈 객체를 인자로 전달해야 한다.

const userAge = {
    name:'홍길동',
    age:25
}
 
const userEmail = {
    name:'홍길동',
    email:'link2me@gmail.com'
}
 
/***
 * Object.assign(target, ...sources);
 * target : 출처 객체의 속성을 복사해 반영한 후 반환할 객체
 * source : 목표 객체에 반영하고자 하는 속성들을 갖고 있는 객체들
 * 목표 객체의 속성 중 출처 객체와 동일한 키를 갖는 속성의 경우,
 * 그 속성 값은 출처 객체의 속성 값으로 덮어쓴다.
 */
const target = Object.assign({}, userAge, userEmail);
console.log(target);
// { name: '홍길동', age: 25, email: 'link2me@gmail.com' }
console.log(userAge);
// { name: '홍길동', age: 25 }
console.log(target === userAge); // false
 
const a = { k: 123 }
const b = { k: 123 }
console.log(a === b); // false
 

 

 

 
const userAge = {
    name:'홍길동',
    age:25
}
 
const userEmail = {
    name:'홍길동',
    email:'link2me@gmail.com'
}
 
/***
 * Object.assign(target, ...sources);
 * target : 출처 객체의 속성을 복사해 반영한 후 반환할 객체
 * source : 목표 객체에 반영하고자 하는 속성들을 갖고 있는 객체들
 * 목표 객체의 속성 중 출처 객체와 동일한 키를 갖는 속성의 경우,
 * 그 속성 값은 출처 객체의 속성 값으로 덮어쓴다.
 */
const target = Object.assign(userAge, userEmail);
console.log(target);
// { name: '홍길동', age: 25, email: 'link2me@gmail.com' }
console.log(userAge);
// { name: '홍길동', age: 25, email: 'link2me@gmail.com' }
console.log(target === userAge); // true
 
const a = { k: 123 }
const b = { k: 123 }
console.log(a === b); // false (서로 다른 객체)
 

 

블로그 이미지

Link2Me

,
728x90

한 마디로 클로저란, 함수가 선언될(생성될) 그 당시에 주변의 환경과 함께 갇히는 것을 말한다.
함수가 속한 렉시컬 스코프(Lexical Environment)를 기억하여, 함수가 렉시컬 스코프 밖에서 실행될 때도 이 스코프에 접근할 수 있게 해주는 기능이다.
렉시컬 스코프란 함수가 선언이 되는 위치에 따라서 상위 스코프가 결정되는 스코프다.
내부함수는 외부함수의 지역변수에 접근할 수 있는데 외부함수의 실행이 끝나서 외부함수가 소멸된 이후에도 내부함수가 외부함수의 변수에 접근할 수 있는 것

 

/***
 * 자바스크립트에는 클로저라는 기능이 있다.
 * 클로저는 함수와 그 함수를 둘러싸고 있는 주변의 상태를 기억하는 기능이다.
 * 클로저는 자바스크립트 고유의 개념이 아니라
 * 함수를 일급 객체로 취급하는 함수형 프로그래밍 언어에서 사용되는 중요한 특성이다.
 * 클로저가 가장 유용하게 사용되는 상황은 현재 상태를 기억하고 변경된 최신 상태를 유지하는 것이다.
 */
 
function makeAdd2(v1) {
  // 함수 makeAdd 내에서 내부함수가 선언되고 호출되었다.
  return function (v2) {
    //  이때 내부함수는 자신을 포함하고 있는 외부함수 makeAdd 변수 v1 접근할 수 있다.
    return v1 + v2;
  };
}
 
function makeAdd(v1){
  // 함수 makeAdd 내에서 내부함수 innerFunc가 선언되고 호출되었다.
  let innerFunc = function (v2){
    //  이때 내부함수 innerFunc는 자신을 포함하고 있는 외부함수 makeAdd 변수 v1 접근할 수 있다.
    return v1 + v2;
  }
  return innerFunc;
}
 
const add3 = makeAdd(3);
console.log(add3); // [Function innerFunc]
console.log(add3(10));
const add7 = makeAdd(7);
console.log(add7(10));
 

 

 

 
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>closure</title>
    <script defer src="./main.js"></script>
</head>
<body>
<p>클로저를 사용한 Counting</p>
<button id="inclease">+</button>
<p id="count">0</p>
<script>
    const incleaseBtn = document.getElementById('inclease');
    const count = document.getElementById('count');
 
    const increase = (function () {
        // 카운트 상태를 유지하기 위한 변수
        let counter = 0;
        // 클로저를 반환
        return function () {
            return ++counter;
        };
    }());
 
    incleaseBtn.onclick = function () {
        count.innerHTML = increase();
    };
</script>
</body>
</html>

 

 

블로그 이미지

Link2Me

,
728x90

일급 객체(First Class citizen)
1. 변수(variable)에 담을 수 있다.
2. 파라미터로 전달할 수 있다.
3. 함수의 반환 값으로 사용할 수 있다.

 

/***
 * first class citizen(1급 객체)
 * 변수에 할당(assignment)할 수 있다.
 * 다른 함수를 인자(argument)로 전달 받는다.
 * 다른 함수의 결과로서 리턴될 수 있다.
 */
 
function mul(num1, num2) {
    return num1 * num2;
}
 
/***
 * func는 매개변수, 이름은 func이건 mul이건 상관없음
 * 매개변수(parameter)로 func를 받았고, 함수(func)를 리턴하기 때문에 고차함수
 * @param func : func()의 매개변수가 2개라면 mulNum()의 매개변수도 2개이여야함
 * @param number1
 * @param number2
 * @returns {*}
 */
function mulNum(func, number1, number2) {
    return func(number1, number2);
}
 
// 전달인자(argument)로 받은 함수인 mul은 콜백함수
let result = mulNum(mul, 34);
console.log(result);
 
// 다른 함수의 결과로 리턴 될 수 있다.
function add(num1) {
    return function (num2) {
        return num1 + num2;
    }
}
 
const rs_add = add(3)(4);
console.log(rs_add);

 

 

'React > morden javascript' 카테고리의 다른 글

JavaScript Object.assign()  (0) 2023.10.17
Javascript 클로저(Closure)  (0) 2023.10.06
[ES2020] optional chaining  (0) 2022.12.28
[ES6] 비구조화 할당(destructuring assignment)  (0) 2022.12.28
Javascript Array.filter 사용 예제  (0) 2022.12.27
블로그 이미지

Link2Me

,
728x90

Optional Chaining은 ES2020에서 등장한  '?.' 연산자는 체인으로 이루어진 각 참조가 유효한지 명시적으로 검증하지 않고 연결된 객체 체인 내에 깊숙이 위치한 속성 값을 읽을 수 있다.

Node.js의 경우 버전 14부터 지원한다.

 

참조가 null 혹은 undefined여도 에러를 출력하지 않고 undefined 값을 리턴한다.

함수 호출시에도 마찬가지로 값이 없다면 undefined를 리턴한다.

 

옵셔널 체이닝 앞의 변수는 꼭 선언되있어야 한다.

const obj = {
    name'Alice',
    cat: {
        name'Dinah'
    }
};
 
const dogName = obj.dog?.name;
console.log(dogName); // output: undefined
 
console.log(obj.someNonExistentMethod?.()); // output: undefined
 
let arr = [12345]
console.log(arr?.[4]);
console.log(arr?.[5]); // undefined
arr[5= 6;
console.log(arr?.[5]);
 
// optional chaining은 값을 읽고 삭제할때에는 사용할 수 있지만
// 값을 할당할 때는 사용할 수 없다.
let user = {
    age: 35
}
//user?.name = '홍길동'; // undefined = '홍길동'
// undefined가 반환되었을 때 null 병합 연산자(??)를 사용해 기본 값을 할당할 수 있다.
user.name = user?.name ?? '홍길동';
console.log(user.name, user.age);

 

optional chaining 이 브라우저에 따라 동작이 안될 수 있으니 반드시 확인해야 한다.

블로그 이미지

Link2Me

,
728x90

ES6부터 비구조화 할당(Destructuring Assignment)이라는 새로운 자바스크립트 표현식이 추가되었다.

비구조화할당이란 배열이나 객체의 속성 혹은 값을 해체하여 그 값을 변수에 각각 담아 사용하는 자바스크립트 표현식이다.

 

/***
 * 비구조화 할당의 기본 구조는 좌측에는 변수, 우측에는 해당 변수에 넣어지는 값을 표현한다.
 * 배열의 경우 []를 사용하고, 객체의 경우 {}를 사용한다.
 
 const [변수명1, 변수명2, 변수명3] = [값1, 값2, 값3];
 const [변수명1, 변수명2, 변수명3 = 기본값] = [값1, 값2];
 
 const 배열명 = [값1, 값2, 값3];
 const [변수명1, 변수명2, 변수명3] = 배열명;
 
 const {변수명1,변수명2,변수명3} = {
     속성명1: 값1,
     속성명2: 값2,
     속성명3: 값3
 };
 
*/
 
const arr = [1];
const [a = 10, b = 20= arr;
// 배열 값이 있으면 변수 기본 값은 무시한다.
console.log({ a, b });
 
const fruits = ['apple''banana''cherry''peach']
const [apple, ...etc] = fruits;
console.log(apple);
console.log(etc);

// JSON 객체에서는 우측의 key 값이 좌측의 변수명과 매칭된다.
const { cat, dog, tiger } = {
    cat: 'CAT',
    dog: 'DOG',
    tiger: 'TIGER'
};
 
console.log(cat);
console.log(dog);
console.log(tiger);

전개 연산자(...)를 이용하면 하나의 변수를 할당하고 나머지 값들을 모두 넣어준다.

전개 연산자를 사용하려면 반드시 가장 마지막 요소에 넣어줘야 한다.

나머지 요소의 오른쪽 뒤에 쉼표가 있으면 SyntaxError가 발생한다.
var [a, ...b,] = [1, 2, 3];

 

 

const arr2 = [123];
const [first, ...rest1] = arr2;
console.log(rest1); // 컴마 개수 이후의 모든 나머지 [2,3]
const [aa, bb, cc, ...rest2] = arr2;
console.log(rest2); // 빈 배열 []
 
const obj = { age: 36name'이순신' };
const { age, name } = obj;
console.log({ age, name });
const { ao, bo } = obj; // 객체에 없는 변수를 할당하면??
console.log({ao, bo}); // { ao: undefined, bo: undefined }
 
const obj2 = { age2: undefined, name2: null, grade2: 'A' };
const { age2 = 0, name2 = 'noName', grade2 = 'F' } = obj2;
console.log({ age2, name2, grade2 }); // { age2: 0, name2: null, grade2: 'A' }
// undefined 인 경우에만 기본값으로 대체된다.

 

 

블로그 이미지

Link2Me

,
728x90

Array filter 메서드는 조건을 만족하는 요소만 모아서 새로운 배열을 반환한다.

const arr = [1581012151620];
 
/***
* Array.prototype.filter() 메서드는 조건을 만족하는 요소만 모아서 새로운 배열을 리턴
 */
const rs1 = arr.filter(x => x % 5 == 0); // 조건 : 5의 배수
console.log(rs1);
 
// filter 메서드 대신 find 메서드를 사용하면 어떤 결과를 반환할까?
console.log(arr.find(x => x % 5 == 0)); // find 메서드는 단 하나의 요소만 리턴
 
console.log(arr.filter((item) => item >= 12)); // 조건 : 12보다 큰 수
 
const users = [
    { name'지민', salary : 7000000 },
    { name'철수', salary : 2500000 },
    { name'재석', salary : 3200000 },
    { name'종민', salary : 4600000 },
];
 
testJson = JSON.stringify(users);
const newJson = JSON.parse(testJson).filter(function(item){
    console.log(item);
    return item.name == "종민";
});
console.log(newJson);
 
// 화살표 함수로 조건을 쉽게 사용 가능
const newUser = users.filter(item => item.name == "종민");
console.log(newUser);
 
const users2 = {
    class : "1-1",
    subject : "English",
    scores : [
        { name : "길동", score : 60 },
        { name : "재섭", score : 80 },
        { name : "현수", score : 100 },
        { name : "희성", score : 70 },
        { name : "광수", score : 40 },
        { name : "혜리", score : 90 }
    ]
};
 
// 점수가 80점 이상인 학생들
const rs3 = users2.scores.filter(item => item.score >= 80);
console.log(rs3);
 
// 점수가 70 ~ 90 사이인 학생들
const rs4 = users2.scores.filter(item => item.score >= 70 && item.score <= 90);
console.log(rs4);

 

 

 

블로그 이미지

Link2Me

,
728x90

Definition and Usage
map() creates a new array from calling a function for every array element.
map() calls a function once for each element in an array.
map() does not execute the function for empty elements.
map() does not change the original array.

map을 이용하면 원 배열을 변경하지 않고 새로운 배열을 만든다.

map은 forEach와 마찬가지로 Array 각 요소를 순회하며 callback 함수를 실행한다. callback에서 return 되는 값을 배열로 반환한다.

 

const arr = [123];
const new_arr = new Array(123);
 
console.log('arr',arr);
console.log('new_arr',new_arr);
console.log(typeof arr === "object");
console.log(Object.values(arr));
 
// Array map() 함수를 이용하여 배열의 요소들을 변경하여 새로운 배열로 리턴
const arr1 = [12345];
 
const result1 = arr1.map(x => x + 1);
console.log('result1', result1);
 
const result_map = arr1.map(x => x * x);
console.log('result_map',result_map);
 
const result_old = [];
for (i = 0; i < arr1.length; i++) {
   result_old.push(arr1[i] * arr1[i]);
}
console.log('result_old',result_old);
 
const result3 = arr1.map(function (x,index){
   console.log(`arr1[${index}] = ${x}`);
   return x*3;
});
console.log('result3',result3);
 
 
const users = [
   { name'지민', age: 22 },
   { name'철수', age: 32 },
   { name'재석', age: 21 },
   { name'종민', age: 35 },
];
 
// 특정 요소만 재정의
const newUsers = users.map(user => {
   if (user.name === '철수') {
      return { ...user, age: 38 };
   }
   return { ...user };
});
console.log(newUsers);
// keys() is not supported in Internet Explorer 11 (or earlier).
console.log(Object.keys(newUsers));
console.log(Object.values(newUsers));
// The entries() method is not supported in Internet Explorer 11 (or earlier).
console.log(Object.entries(newUsers));
for (const [key, value] of Object.entries(newUsers)) {
   console.log(key, value);
}
 
/***
 * 자바스크립트엔 여덟 가지 자료형(숫자형, bigint형, 문자형, 불린형, 객체형, Null형, Undefined형, 심볼형)이 있다.
 * const 키워드에 객체를 할당하면 당연히 객체를 가리키는 주소 값이 할당된다. 그리고 이 주소 값은 불변이다.
 * 객체는 참조값을 통해 관리되고 있어 객체의 속성 값이 재할당 되더라도 오류가 발생되지 않는다.
 */
users[0].age = 18// const 키워드로 선언된 객체의 속성값은 재할당할 수 있다.
console.log(users);

 

 

 

블로그 이미지

Link2Me

,
728x90

"카카오 맵 키워드로 장소검색하고 목록으로 표출하기" 로 검색된 결과 URL 이다.

https://apis.map.kakao.com/web/sample/keywordList/

위 UTL 예시에 나온 코드로는 부족하므로 클러스터링 등 내용을 더 찾아서 살을 붙여야 한다.

 

화면 구성을 위해서 아래와 같이 HTML 을 변경한다.

아래 HTML 코드에서 카카오맵 API Key는 삭제했다.

<html>
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex,nofollow"/>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>카카오지도</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css">
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/mdb.lite.css">
<link rel="stylesheet" href="/css/jquery-ui.css">
<link rel="stylesheet" href="/css/kakaomap.css"/>
</head>
<body>
<div class="card">
<div class="my-0 mx-2">
    <div class="form-check form-check-inline">
        <button type="button" class="btn btn-outline-primary btn-sm px-2" id="searchToggle">OFF</button>
    </div>
 
    <div class="form-check form-check-inline">
        <p class="fs-4">반경</p>
    </div>
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" name="radius" id="dis1" value="0.5" checked />
      <label class="form-check-label" for="dis1">0.5</label>
    </div>
 
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" name="radius" id="dis2" value="1.0" />
      <label class="form-check-label" for="dis2">1</label>
    </div>
 
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" name="radius" id="dis3" value="1.5" />
      <label class="form-check-label" for="dis3">1.5</label>
    </div>
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" name="radius" id="dis4" value="2.0" />
      <label class="form-check-label" for="dis4">2</label>
    </div>
 
    <div class="form-check form-check-inline">
        <button type="button" class="btn btn-outline-primary btn-sm px-2" id="curLoc">현위치</button>
    </div>
 
</div>
<div class="mt-1 mb-2 mx-2">
    <div class="map_wrap">
        <div id="map" style="width:100%;height:800px;position:relative;overflow:hidden;"></div>
 
        <div id="menu_wrap" class="bg_white">
            <div class="option">
                <div class="form-check form-check-inline">
                    <form onsubmit="searchPlaces(); return false;">
                        <input type="text" value="" id="keyword" size="15"> 
                        <button type="submit">&nbsp;검색</button>
                    </form>
                    <img src="./marker/icon_eraser.png" alt="clear" height="30" width="30" style="margin-left: 10px;" id="eraser">
                </div>
            </div>
            <div id="datacount"></div>
            <hr>
            <ul id="placesList"></ul>
            <div id="pagination"></div>
        </div>
        <div id="dialog" title="지도 Infowindow"></div>
    </div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script type="text/javascript" src="/js/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/js/mdb.lite.min.js"></script>
<script type="text/javascript" src="/js/jquery-ui.js"></script>
<script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey=&libraries=services,clusterer,drawing"></script>
<script type="text/javascript" src="Map.js"></script>
<script>
$("#searchToggle").click(function(){
    // 지도 검색창 ON/OFF
    if($("#menu_wrap").css("display")=="none"){
        $("#menu_wrap").show();
        $("#searchToggle").text('OFF');
    } else {
        $("#menu_wrap").hide();
        $("#searchToggle").text('ON');
    }
});
 
$("input[name='radius']").change(function(){
    searchPlaces();
});
$("#curLoc").click(function(){
    // 현재 지도의 중심좌표 구하기
    searchPlaces();
});
 
$("#eraser").click(function(){
    $("#keyword").val('');
});
</script>
</body>
</html>

 

Map.js

변수는 let 과 const 로 전부 변경하고, Ajax 로 PHP와 연동된 DB 자료를 가져다가 출력하는 걸 만든다.

    // 마커를 담을 배열입니다
    let markers = [];
 
    const mapContainer = document.getElementById('map'), // 지도를 표시할 div
    mapOption = {
        center: new kakao.maps.LatLng(37.566826126.9786567), // 지도의 중심좌표
        level: 12 // 지도의 확대 레벨
    };
 
    // 지도를 생성합니다
    const map = new kakao.maps.Map(mapContainer, mapOption);
 
    // 마커 클러스터러를 생성합니다
    const clusterer = new kakao.maps.MarkerClusterer({
        map: map, // 마커들을 클러스터로 관리하고 표시할 지도 객체
        averageCenter: true// 클러스터에 포함된 마커들의 평균 위치를 클러스터 마커 위치로 설정
        minLevel: 6 // 클러스터 할 최소 지도 레벨
    });
 
    // 일반 지도와 스카이뷰로 지도 타입을 전환할 수 있는 지도타입 컨트롤을 생성합니다
    const mapTypeControl = new kakao.maps.MapTypeControl();
 
    // 지도에 컨트롤을 추가해야 지도위에 표시됩니다
    // kakao.maps.ControlPosition은 컨트롤이 표시될 위치를 정의하는데 TOPRIGHT는 오른쪽 위를 의미합니다
    map.addControl(mapTypeControl, kakao.maps.ControlPosition.TOPRIGHT);
 
    // 지도 확대 축소를 제어할 수 있는  줌 컨트롤을 생성합니다
    const zoomControl = new kakao.maps.ZoomControl();
    map.addControl(zoomControl, kakao.maps.ControlPosition.RIGHTBOTTOM);
 
    // 지도가 이동, 확대, 축소로 인해 중심좌표가 변경되면 마지막 파라미터로 넘어온 함수를 호출하도록 이벤트를 등록합니다
    let getLat = null;
    let getLng = null;
    kakao.maps.event.addListener(map, 'center_changed'function() {
        // 지도의  레벨을 얻어옵니다
        const level = map.getLevel();
        // 지도의 중심좌표를 얻어옵니다
        const latlng = map.getCenter();
        console.log('중심 위도: '+latlng.getLat() + ', 경도: ' + latlng.getLng());
        getLat = latlng.getLat();
        getLng = latlng.getLng();
    });
 
    // 장소 검색 객체를 생성합니다
    const ps = new kakao.maps.services.Places();
 
    // 검색 결과 목록이나 마커를 클릭했을 때 장소명을 표출할 인포윈도우를 생성합니다
    const infowindow = new kakao.maps.InfoWindow({zIndex:1});
 
    // 키워드로 장소를 검색합니다
    searchPlaces();
 
    // 키워드 검색을 요청하는 함수입니다
    function searchPlaces() {
        let keyword = document.getElementById('keyword').value;
        let radius = $("input[name='radius']:checked").val();
 
        $.ajax({
            url : 'ajaxMap.php',
            type : 'GET',
            data : { 'msg': keyword, 'radius':radius, 'lat':getLat, 'lng':getLng },
            dataType: 'json',
            success : function(json) {
                if(json.length == 0) {
                    alert('검색 데이터가 없습니다.');
                    return;
                }
 
                console.log('데이터 갯수 :: ' + json.length);
                displayPlaces(json);
 
                // 클러스터에 마커들을 추가합니다
                clusterer.addMarkers(markers);
 
                var pagination = [ '1''2''3' ];
                displayPagination(pagination);
            },
            error : function(xhr, status, error){
                alert("에러코드 : " + xhr.status); //요청에 실패하면 에러코드 출력
            },
            complete : function() {
                
            }
        });
    }
 
    // 장소검색이 완료됐을 때 호출되는 콜백함수 입니다
    function placesSearchCB(data, status, pagination) {
        if (status === kakao.maps.services.Status.OK) {
            // 정상적으로 검색이 완료됐으면 검색 목록과 마커를 표출합니다
            displayPlaces(data);
 
            // 페이지 번호를 표출합니다
            displayPagination(pagination);
        } else if (status === kakao.maps.services.Status.ZERO_RESULT) {
            alert('검색 결과가 존재하지 않습니다.');
            return;
        } else if (status === kakao.maps.services.Status.ERROR) {
            alert('검색 결과 중 오류가 발생했습니다.');
            return;
        }
    }
 
    // 검색 결과 목록과 마커를 표출하는 함수입니다
    function displayPlaces(places) {
        let listEl = document.getElementById('placesList'),
        menuEl = document.getElementById('menu_wrap'),
        fragment = document.createDocumentFragment(),
        bounds = new kakao.maps.LatLngBounds(),
        listStr = '';
 
        // 검색 결과 목록에 추가된 항목들을 제거합니다
        removeAllChildNods(listEl);
 
        // 지도에 표시되고 있는 마커를 제거합니다
        removeMarker();
 
        const cntEl = document.getElementById('datacount');
        cntEl.innerText = '검색 개수 : ' + places.length;
 
 
        for (let i=0; i<places.length; i++) {
 
            let color_marker = "marker-icon-blue.png";
 
            if (places[i].yn == 0)  { // 없으면 => 빨간색
                color_marker = "marker-icon-red.png";
                if(places[i].isbiz > 0) {
                    color_marker = "marker-icon-green.png";
                }
            } else {
                color_marker = "marker-icon-blue.png";
                if(places[i].isbiz > 0) {
                    color_marker = "marker-icon-orange.png";
                }
            }
 
            // 마커를 생성하고 지도에 표시합니다.
            let idx = places[i].idx; // 절대 var 변수를 선언하면 안된다. 반드시 let 변수를 선언해야 제대로 동작되더라. 개삽질을 엄청했다.
            let title = places[i].idx;
            let placePosition = new kakao.maps.LatLng(places[i].latitude, places[i].longitude);
            let marker = addMarkers(placePosition, color_marker, title);
            let itemEl = getListItem(i, places[i], color_marker); // 검색 결과 항목 Element를 생성합니다
 
            // 검색된 장소 위치를 기준으로 지도 범위를 재설정하기위해 LatLngBounds 객체에 좌표를 추가합니다
            bounds.extend(placePosition);
 
            // 마커와 검색결과
            // 항목에 mouseover 했을때 해당 장소에 인포윈도우에 장소명을 표시합니다. mouseout 했을 때는 인포윈도우를 닫습니다
            (function(marker, title) {
                kakao.maps.event.addListener(marker, 'mouseover'function() {
                    displayInfowindow(marker, title);
                });
 
                kakao.maps.event.addListener(marker, 'mouseout'function() {
                    infowindow.close();
                });
 
                itemEl.onmouseover =  function () {
                    displayInfowindow(marker, title);
                };
 
                itemEl.onmouseout =  function () {
                    infowindow.close();
                };
 
                // 마커에 클릭 이벤트를 등록한다.
                kakao.maps.event.addListener(marker, 'click'function() {
                    //map.panTo(placePosition); // 지도 중심을 부드럽게 이동시킨다.
                    console.log('idx:' + idx);
                    custom_infowindow(idx);
 
                });
 
            })(marker, places[i].bldNM);
 
            fragment.appendChild(itemEl);
        }
 
        // 검색결과 항목들을 검색결과 목록 Elemnet에 추가합니다
        listEl.appendChild(fragment);
        menuEl.scrollTop = 0;
 
        // 검색된 장소 위치를 기준으로 지도 범위를 재설정합니다
        map.setBounds(bounds);
    }
 
    function custom_infowindow(idx){
        $('#dialog').load('infowindow.php?do='+idx, function() {
            $(this).dialog({
                autoOpen : true,
                height : 'auto',
                width : 'auto',
                position: { my: "center", at: "center", of: window },
                title : 'XX정보',
                buttons : {
                    "닫기" : function() {
                        $(this).dialog("close");
                    }
                }
            });
        });
 
    }
 
    // 검색결과 항목을 Element로 반환하는 함수입니다. 위도, 경도, 번호, 건물명, 도로명주소, 지번주소
    function getListItem(index, places, _color) {
        let el = document.createElement('li'),
        itemStr = '<span style="float:left;position:absolute;width:33px; height:31px;margin:10px 0 0 10px;"><img width="31" height="31" src="./marker/' + _color + '"></span>' +
                  '<div class="info">' +
                  '   <h5>' + places.bldNM + '</h5>';
 
        if (places.stAddress) {
            itemStr += '   <span>' + places.stAddress + '</span>' +
                       '   <span class="jibun gray">' +  places.jiAddress  + '</span>';
        } else {
            itemStr += '   <span>' +  places.jiAddress  + '</span>';
        }
 
        itemStr     += '  <span class="tel">' + places.idx  + '</span>' +
                       '</div>';
 
        el.innerHTML = itemStr;
        el.className = 'item';
 
        return el;
    }
 
 
    function addMarkers(position, _color, title) {
        const imageSrc = './marker/' + _color;
        const imageSize = new kakao.maps.Size(3333);
        const imageOptions = {
            offset: new kakao.maps.Point(2769)
        };
 
        const markerImage = new kakao.maps.MarkerImage(imageSrc, imageSize, imageOptions)
        // 마커를 생성합니다
        const marker = new kakao.maps.Marker({
            position: position,
            //title: title,
            image: markerImage
        });
 
 
        marker.setMap(map); // 마커가 지도 위에 표시되도록 설정합니다
        markers.push(marker); // 생성된 마커를 배열에 추가합니다
 
        return marker;
    }
 
    // 지도 위에 표시되고 있는 마커를 모두 제거합니다
    function removeMarker() {
        //clusterer.removeMarkers(markers);
        clusterer.clear(); // 추가된 모든 마커 삭제
        for ( let i = 0; i < markers.length; i++ ) {
            markers[i].setMap(null);
        }
        markers = [];
    }
 
    // 검색결과 목록 하단에 페이지번호를 표시는 함수입니다
    function displayPagination(pagination) {
        let paginationEl = document.getElementById('pagination'),
            fragment = document.createDocumentFragment(),
            i;
 
        // 기존에 추가된 페이지번호를 삭제합니다
        while (paginationEl.hasChildNodes()) {
            paginationEl.removeChild (paginationEl.lastChild);
        }
 
        for (i=1; i<=pagination.last; i++) {
            let el = document.createElement('a');
            el.href = "#";
            el.innerHTML = i;
 
            if (i===pagination.current) {
                el.className = 'on';
            } else {
                el.onclick = (function(i) {
                    return function() {
                        pagination.gotoPage(i);
                    }
                })(i);
            }
 
            fragment.appendChild(el);
        }
        paginationEl.appendChild(fragment);
    }
 
    // 검색결과 목록 또는 마커를 클릭했을 때 호출되는 함수. 인포윈도우에 장소명을 표시합니다
    function displayInfowindow(marker, title) {
        const content = '<div style="padding:5px;z-index:1;">' + title + '</div>';
 
        infowindow.setContent(content);
        infowindow.open(map, marker);
    }
 
    // 검색결과 목록의 자식 Element를 제거하는 함수입니다
    function removeAllChildNods(el) {
        while (el.hasChildNodes()) {
            el.removeChild (el.lastChild);
        }
    }
 
 

 

백엔드 PHP 코드는 여기에는 적지 않는다.

화면에 뿌리는 marker 의 개수와 성능은 백엔드 Query를 어떻게 구현하느냐에 따라 달라진다.

가능하면 SELECT 문의 결과를 최소로 하여 원하는 결과를 찾을 수 있게 구현한다.

 

 

 

 

 

 

'React > morden javascript' 카테고리의 다른 글

Javascript Array.filter 사용 예제  (0) 2022.12.27
Javascript Array.map 사용 예제  (2) 2022.12.27
[Javascript] 정규표현식  (0) 2022.10.08
[Javascript] _cloneDeep()  (0) 2022.10.05
[ES6] Spread 연산자  (0) 2022.10.02
블로그 이미지

Link2Me

,
728x90

자바스크립트 정규표현식 생성

1. 생성자 방식

    RegExp 생성자 함수를 호출하여 사용할 수 있다.

// new RegExg(표현식)
const regexp1 = new RegExp("^abc");
 
// new RegExg(표현식, 플래그)
const regexp2 = new RegExp("^abc""gi");
const regexp1 = new RegExp(/^abc/i); // ES6
const regexp2 = new RegExp(/^abc/'i');
const regexp3 = new RegExp('^abc''i');

 

 

2. 리터럴 방식

// 정규표현식은 /로 감싸진 패턴을 리터럴로 사용한다.
// 정규 표현식 리터럴은 패턴(pettern)과 플래그(flag)로 구성된다.
const regexp1 = /^abc/;  // --> /패턴/
const regexp2 = /^abc/gi; // --> /패턴/플래그

 

 

자바스크립트 메소드

문법   설명
정규식.exec(문자열)                         일치하는 하나의 정보(Array) 반환
정규식.test(문자열)                           일치 여부(Boolean) 반환
문자열.match(정규식)                       일치하는 문자열의 배열(Array) 반환
문자열.search(정규식)                      일치하는 문자열의 인덱스(Number) 반환
문자열.replace(정규식,대체문자)     일치하는 문자열을 대체하고 대체된 문자열(String) 반환
문자열.split(정규식)                          일치하는 문자열을 분할하여 배열(Array)로 반환
생성자_정규식.toString()                  생성자 함수 방식의 정규식을 리터럴 방식의 문자열(String)로 반환

 

 

For example a(?=b) will match the "a" in "ab", but not the "a" in "ac".

Whereas a(?!b) will match the "a" in "ac", but not the "a" in "ab".

const regexr = /.+(?=:)/;  // positive 전방 탐색(lookahead)
const str = 'https://www.abc.com';
console.log(regexr.exec(str));  // 결과 : https
console.log(str.match(regexr)); // 결과 : https

 

const regexr = /.(?!.)/gi; // 부정형 전방탐색(negative lookahead)
const str = '홍길동';
console.log(regexr.exec(str));  // 결과 : 동
console.log(str.replace(regexr, '*')); // 결과 : 홍길*

 

정규표현식 기본적인 이해는 https://www.nextree.co.kr/p4327/ 를 참조하면 도움된다.

https://heropy.blog/2018/10/28/regexp/

'React > morden javascript' 카테고리의 다른 글

Javascript Array.map 사용 예제  (2) 2022.12.27
카카오 맵 장소 검색 구현 방법  (0) 2022.12.19
[Javascript] _cloneDeep()  (0) 2022.10.05
[ES6] Spread 연산자  (0) 2022.10.02
자바스크립트 Object  (0) 2022.06.11
블로그 이미지

Link2Me

,
728x90

현재 폴더에 package.json 추가된다.
npm init –y

 

개발용 의존성 패키지 설치 : 개발할 때만 필요하다.  --save-dev 대신에 -D
npm install parcel-bundler –D

 

원하는 버전을 명시하여 버전 설치
npm install lodash@4.17.20

최신버전의 정보를 보여준다.
npm info lodash

package.json 이 있는 곳에서 명령어를 입력해야 한다.
npm update lodash

package.json 파일이 있으면 node_module 을 설치할 수 있다.
package.josn 파일과 package-lock.json 파일을 삭제되지 않게 조심해야 한다.
npm install

 

{
  "name""ex01",
  "version""1.0.0",
  "scripts": {
    "dev""parcel index.html",
    "build""parcel build index.html"
  },
  "keywords": [],
  "author""",
  "license""ISC",
  "description""",
  "dependencies": {
    "lodash""^4.17.21"
  },
  "type""module"
}

Cannot use import statement outside a module 와 같은 에러 메시지가 발생하면

위와 같이 package.json에  "type": "module" 을 추가해주면 해결된다.

 

형변환(Type conversion)
=== 일치연산자
== 동등연산자 : 형변환이 발생한다.

 

객체는 참조타입(reference type)이기 때문에 할당 연산자 (=) 를 사용하면 메모리 주소값이 복사된다.

Spread operator 를 사용하여 의도적으로 얕은 복사(Shallow Copy)를 할 수 있다.

깊은 복사는 lodash 모듈을 설치해서 이용하면 편리하다.

loash 에서 제공하는 얕은 복사 함수는 _.clone(object) 이다.

loash 에서 제공하는 깊은 복사 함수는 _.cloneDeep(object) 이다.

import _ from 'lodash';
 
const user = {
    name'홍길동',
    age : 25,
    emails: ['link2me@test.com']
}
 
const copyUser = _.cloneDeep(user);
console.log(copyUser === user); // 메모리 주소가 같은가?
 
user.age = 30;
user.emails.push('jsk005@test.com');
console.log('user', user);
console.log('copyUser', copyUser);

결과

 

 

 

 

 

 

 

 

 

'React > morden javascript' 카테고리의 다른 글

카카오 맵 장소 검색 구현 방법  (0) 2022.12.19
[Javascript] 정규표현식  (0) 2022.10.08
[ES6] Spread 연산자  (0) 2022.10.02
자바스크립트 Object  (0) 2022.06.11
자바스크립트 호이스팅(Hoisting)  (0) 2022.06.10
블로그 이미지

Link2Me

,
728x90

ES6에서는  '...'와 같이 다소 특이한 형태의 문법이 추가되었다. 
점 3개가 연달아 붙어있는 이 표시는 Spread Opertor(스프레드 오퍼레이터, 전개 연산자)를 나타내는 것으로, 배열, 함수, 객체 등을 다루는 데 있어서 매우 편리하고 재미있는 새로운 기능을 제공한다.

 

const numbersOne = [123];
const numbersTwo = [456];
const numbersCombined = [...numbersOne, ...numbersTwo];

 

 

const numbers = [123456];
 
const [one, two, ...rest] = numbers;

컴마 개수 이후의 값이 rest 값이다.

 

const arr1 = [012];
const arr2 = [345];
 
// (1) 배열 복사
const arr3 = [...arr1]; // arr3은 [0, 1, 2]
 
// (2) 배열에 추가 요소로 넣기
const arr4 = [12, ...arr2, 910]; // arr4는 [1, 2, 3, 4, 5, 9, 10]
 
// (3) 두 배열 이어 붙이기
const arr5 = [...arr1, ...arr2]; // [0, 1, 2, 3, 4, 5];

 

'React > morden javascript' 카테고리의 다른 글

[Javascript] 정규표현식  (0) 2022.10.08
[Javascript] _cloneDeep()  (0) 2022.10.05
자바스크립트 Object  (0) 2022.06.11
자바스크립트 호이스팅(Hoisting)  (0) 2022.06.10
Javascript this and Class  (0) 2022.06.09
블로그 이미지

Link2Me

,
728x90

객체는 프로퍼티와 메소드의 집합이다.

객체 리터럴을 사용해서 객체를 생성하는 것은 연속된 구조체나 연관된 데이터를 일정한 방법으로 변환하고자 할 때  많이 쓰이는 방법이다.

this 키워드는 지금 동작하고 있는 코드를 가지고 있는 객체를 가리킨다. 아래 예제에서 this 는 user 객체와 동일하다. 

 

// Object(객체 데이터) : 여러 데이터를 key:value 형태로 저장한다. {}
let user = {
    name : 'Json',
    nickname : 'Link2Me',
    age : 25,
    getName: function () { // 메소드(Method)
        console.log(`이름:${this.name}, 별명:${this.nickname}, 나이:${this.age}`)
    }
};
 
console.log(user.name);
console.log(user.nickname);
console.log(user.age);
user.getName();

 

 

'React > morden javascript' 카테고리의 다른 글

[Javascript] _cloneDeep()  (0) 2022.10.05
[ES6] Spread 연산자  (0) 2022.10.02
자바스크립트 호이스팅(Hoisting)  (0) 2022.06.10
Javascript this and Class  (0) 2022.06.09
javascript 콜백 함수(callback function)  (0) 2022.05.27
블로그 이미지

Link2Me

,
728x90

변수의 선언을 해당 스코프의 맨 위로 끌어올려졌다. → 호이스팅

console.log(x);
var x = 1;
 
// 위 코드는 아래와 똑같다.
var x;
console.log(x);
= 1;

 

자바스크립트 Hoisting 이란 함수 선언부가 유효범위 최상단으로 끌어올려지는 현상을 말한다.

함수를 하단에 작성하는 것이 좋다.

 

const a = 5;
 
double();
 
function double(){
  console.log(a*2);
}

 

 

타이머 함수

setTimeout(함수, 시간); // 일정시간 후 함수 실행

clearTimeout(); // 설정된 Timeout 함수를 종료

 

setInterval(함수, 시간); // 시간 간격마다 함수 실행

clearInterval();  // 설정된 Interval 함수를 종료

 

 

const timer = setTimeout(()=> {
  console.log('Hello world');
},2000);
 
const h1El = document.querySelector('h1');
h1El.addEventListener('click', ()=> {
  clearTimeout(timer);
});

 

'React > morden javascript' 카테고리의 다른 글

[ES6] Spread 연산자  (0) 2022.10.02
자바스크립트 Object  (0) 2022.06.11
Javascript this and Class  (0) 2022.06.09
javascript 콜백 함수(callback function)  (0) 2022.05.27
javascript 화살표 함수(람다식)  (0) 2022.05.27
블로그 이미지

Link2Me

,
728x90

this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수(self-reference variable)이다.

세부적인 사항은 https://velog.io/@realryankim/JavaScript-this%EB%9E%80 를 참조하면 도움된다.

 

// this
// 일반(normal) 함수는 호출 위치에 따라 this 정의
// 화살표(Arrow) 함수는 자신의 선언된 함수 범위에서 this 정의
 
const link2me = {
    name : 'Link2Me',
    normal: function () {
        console.log(this.name);
    },
    arrow: () => {
        console.log(this.name);
    }
}
 
link2me.normal(); // 결과 : Link2Me
link2me.arrow();  // 결과 : undefined
 
function User(name) {
    this.name = name;
}
 
User.prototype.normal = function () {
    console.log(this.name);
}
 
User.prototype.arrow = () => {
    console.log(this.name);
}
 
const link2u = new User('Link2U');
link2u.normal(); // 결과 : Link2U
link2u.arrow(); // 결과 : undefined

 

ES6 Class

- 자바스크립트에서 클래스는 프로토타입을 이용해서 만들어졌지만 ES5의 클래스 의미와는 다른 문법과 의미를 가진다.

- 자바스크립트에서 클래스 사용은 ES6에서부터 지원을 하기 시작했다. ES5까지 자바스크립트에는 클래스가 없었다.
  익스플로러에서는 해당 코드 사용이 불가능하나, 최신 브라우저를 이용할 경우 class를 지원한다.

  생김새만 클래스 구조이지, 엔진 내부적으로는 프로토타입 방식으로 작동된다.

- Class는 객체를 정의하기 위한 상태(멤버 변수)와 메서드(함수)로 구성된다.

 

클래스 내에서 정의한 메서드는 User.prototype에 저장한다.

class User {
    constructor(first, last) {
        this.firtstName = first;
        this.lastName = last;
    }
    getFullName(){
        return `${this.firtstName} ${this.lastName}`;
    }
}
 
const link2me = new User('Link2Me''Json');
link2me.getFullName();
 
console.log(link2me); // User { firtstName: 'Link2Me', lastName: 'Json' }
console.log(link2me.getFullName()); // Link2Me Json

new User('Link2Me', 'Json') 을 호출하면

1. 새로운 객체가 생성된다.

2. 넘겨받은 인수와 함께 constructor 가 자동으로 실행된다. 매개변수가 변수에 할당된다.

3. 객체의 메서드를 호출하면 메서드를 prototype 프로퍼티를 통해 가져온다.

    이 과정이 있기 때문에 객체에서 클래스 메서드에 접근할 수 있다.

 

클래스는 함수이다. alert(typeof User);

 

정확히는 생성자 메서드와 동일하다.
alert(User === User.prototype.constructor); // true

클래스 내부에서 정의한 메서드는 User.prototype에 저장된다.
alert(User.prototype.getFullName);

현재 프로토타입에는 메서드가 두 개다.
alert(Object.getOwnPropertyNames(User.prototype)); // constructor, getFullName

 

클래스 상속

// 클래스 구현 : 자바스크립트에서 클래스 사용은 ES6에서부터 지원
class Parent {
    sayHello() {
        return 'Hello world, from Parent Class';
    }
}
 
// 클래스 상속
class Child extends Parent {
}
 
const child = new Child();
console.log(child.sayHello());

 

 

 
class Person {
  constructor(name) {
    this.name = name;
  }
  sayHello() {
    console.log(`hello~ ${this.name}!`);
  }
 
  // 부모 클래스에서 클래스 필드로 메서드를 정의하면
  // 자식에서 super를 사용해서 호출할 수 없다.
  // 이 메서드는 프로토타입에 추가되는 것이 아니고, 객체에 추가된다.
  getRandom = () => {
    return Math.floor(Math.random() * 10);
  };
}
 
class Programmer extends Person {
  constructor(name, language) {
    super(name);
    this.language = language;
  }
  sayHello() {
    super.sayHello();
    console.log(`I like ${this.language}.`);
    console.log(`Your lucky number is ${super.getRandom()}`);
    // super는 프로토타입을 기반으로 동작한다.
    // super로 접근하려고 하면 에러가 발생한다. this 로 변경해보라.
  }
 
  // this로 자식에서도 찾고자 한다면 클래스 필드로 정의하면 된다.
  // getRandom = () =>
  getRandom() {
    return 20 + Math.floor(Math.random() * 10);
  }
}
 
const person1 = new Programmer('mike''javascript');
person1.sayHello();
 

 

 

 

class Person {
    age = 25;
    constructor(name) {
        this.name = name;
    }
    sayHello() { // this 인식
        console.log(`hello~ ${this.name}!`);
    }
 
    arrowName = () => {
        console.log(this.name);// this 인식
    };
 
    normalName = function(){
        console.log(this.name); // undefined
    }
}
 
class Programmer extends Person {
    constructor(name, language) {
        super(name);
        this.language = language;
    }
    sayHello() { // 메서드 오버라이딩
        super.sayHello();
        console.log(`${this.name}은 ${this.language} 언어를 좋아합니다.`);
    }
}
 
const p1 = new Person('강감찬');
p1.sayHello();
 
const p2 = new Programmer('홍길동''javascript');
p2.sayHello();
 
console.log(Person.prototype.age, Person.prototype.arrowName); // undefined undefined
console.log(Person.prototype.age, Person.prototype.normalName); // undefined undefined
 
const person1 = new Person('mike');
const person2 = new Person('jane');
person1.age = 50;
console.log(person1.age, person2.age); // 50 25
 
setTimeout(person1.arrowName, 100); // mike
setTimeout(person1.normalName, 100); // undefined
setTimeout(person2.arrowName, 100); // jane
setTimeout(person2.normalName, 100); // undefined
 

 

 

블로그 이미지

Link2Me

,
728x90

자바스크립트는 null과 undefined 타입을 제외하고 모든 것을 객체로 다룬다.
함수를 변수 or 다른 함수의 변수처럼 사용할 수 있다. 함수를 콜백함수로 사용할 경우, 함수의 이름만 넘겨주면 된다.
함수를 인자로 사용할 때 callback 처럼 () 를 붙일 필요가 없다는 것이다.

 

<script>
 
// 콜백(callback)
// 함수의 인수로 사용되는 함수
 
// setTimeout(함수, 시간)
 
function timeout(callback) {
    setTimeout(()=>{
        console.log('Callback function example');
        callback()
    }, 3000);
}
 
timeout(()=>{
    console.log('Done!');
});
 
</script>

 

 

<script>
 
let allUserData = [];
 
// 콘솔에 결과를 찍는 함수
function LogFunc(userData) {
    if ( typeof userData === "string") {
        console.log("string : " + userData);
    } else if ( typeof userData === "object") {
        for (var item in userData) {
            console.log(item + ": " + userData[item]);
        }
    }
}
 
// 두 개의 인자를 받아서 마지막에 콜백함수를 호출한다.
function getInput (options, callback) {
    allUserData.push (options);
    callback (options);
}
 
// getInput 함수를 호출할 때 , 우리는 LogFunc 함수의 이름을 인자로 넘긴다.
// LogFunc은 콜백함수가 되어 getInput 함수의 내부에서 동작 할 것이다.
getInput ({name:"배수지", items:"JavaScript"}, LogFunc);
getInput ("홍길동", LogFunc);
 
</script>

 

 

 

 

'React > morden javascript' 카테고리의 다른 글

자바스크립트 Object  (0) 2022.06.11
자바스크립트 호이스팅(Hoisting)  (0) 2022.06.10
Javascript this and Class  (0) 2022.06.09
javascript 화살표 함수(람다식)  (0) 2022.05.27
변수 유효범위(Variable Scope)  (0) 2022.05.27
블로그 이미지

Link2Me

,
728x90

ECMAScript6 (2015.6월)

자바스크립트에서 화살표 함수 사용법을 알아두자.

 

Node.js 생태계는 무척 잘 되어 있다. 즉 제공되는 기능을 적재적소에 잘 써먹기만 하면 대부분의 문제를 해결할 수 있다.

프론트엔드의 주요 역할은 HTML과 CSS를 이용한 퍼블리싱, 데이터 기반의 상호작용 가능한 UI 구현, 그리고 백엔드와의 HTTPS 통신 정도이다.

대부분의 복잡한 비즈니스 로직은 서버에 탑재된다. 서버(백엔드)는 다량의 데이터를 안전하게 보관하고 내부 동작 방식을 숨길 뿐만 아니라 여러 요청을 동시에 처리하는 데 최적화되어 있다.

 

화살표 함수에 대한 자세한 사항은 https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/Arrow_functions 를 참조하면 된다.

 

화살표 함수 표현(arrow function expression)은 전통적인 함수표현(function)의 간편한 대안이다.

기존의 함수 표현식에서 function 키워드를 삭제하고 인자를 받는 매개변수의 괄호()와 코드블록({}) 사이에 화살표(=>) 만 넣어주면 된다.

 

// () => { }   vs function() { }

 

let func = function(arg1, arg2, ...argN) {
  return expression;
};
 
// 축약버전 : 화살표 함수
let func = (arg1, arg2, ...argN) => expression

 

- 인수가 하나밖에 없다면 인수를 감싸는 괄호를 생략할 수 있다.

let double = n => n * 2;

 

- 인수가 하나도 없을 땐 괄호는 생략할 수 없다.

// 일반 함수
const foo = function () { console.log("foo") }; // foo
 
// 화살표 함수
const foo = () => console.log("foo"); // foo

 

- 본문이 여러 줄로 구성되었다면 중괄호를 사용해야 하고, 반드시 return 으로 결과를 반환해야 한다.

let sum = (a, b) => {  // 중괄호는 여러 줄로 구성되어 있음을 알려준다.
  let result = a + b;
  return result; // 반드시 return 지시자로 결과값을 반환해주어야 한다.
};
 
console.log(sum(34)); // 7
 
let sum = (a, b) => a + b; // 

 

<script>
 
let sum = (a, b) => a + b;
 
/* 위 화살표 함수는 아래 함수의 축약 버전이다.
 
let sum = function(a, b) {
  return a + b;
};
 
*/
</script>

 

 

<script>
// 매개변수 지정 방법
    () => { ... } // 매개변수가 없을 경우
     x => { ... } // 매개변수가 한 개인 경우, 소괄호를 생략할 수 있다.
(x, y) => { ... } // 매개변수가 여러 개인 경우, 소괄호를 생략할 수 없다.
 
// 함수 몸체 지정 방법
=> { return x * x }  // single line block
=> x * x   // 함수 몸체가 한줄 구문이면 중괄호를 생략할 수 있으며 암묵적으로 return된다.
 
() => { return { a: 1 }; }
() => ({ a: 1 })  // 위 표현과 동일하다. 객체 반환시 소괄호를 사용한다.
 
() => {           // multi line block.
  const x = 10;
  return x * x;
};
 
</script>
 

 

 

<script>
 
// ES5
var arr = [123];
var pow = arr.map(function (x) { // x는 요소값
    return x * x;
});
 
console.log(pow); // [ 1, 4, 9 ]


// ES6
const arr = [123];
const pow = arr.map(x => x * x);
 
console.log(pow); // [ 1, 4, 9 ]
 
</script>

 

'React > morden javascript' 카테고리의 다른 글

자바스크립트 Object  (0) 2022.06.11
자바스크립트 호이스팅(Hoisting)  (0) 2022.06.10
Javascript this and Class  (0) 2022.06.09
javascript 콜백 함수(callback function)  (0) 2022.05.27
변수 유효범위(Variable Scope)  (0) 2022.05.27
블로그 이미지

Link2Me

,
728x90

자바스크립트에서 객체나 함수는 모두 변수(variable)이다.

 

var 키워드로 선언된 변수는 함수 레벨 scope를 따름
    함수 레벨 Scope (Function-level scope)
        함수 내에서 선언된 지역 변수는 함수 내에서만 유효
        함수 외부에서는 참조 불가

let, const 키워드로 선언된 변수는 블록 레벨 scope를 따름
    블록 레벨 Scope (Block-level scope)
        코드 블록 내에서 선언된 변수는 코드 블록 내에서만 유효, 코드 블록 외부에서는 참조 불가
        코드 블록 내부에서 선언한 변수는 지역 변수

 

<script>
// 변수 유효범위(Variable Scope)
let a = 3
function name() {
    let a = 20  // let 은 블럭 레벨 범위안에서 유효
    console.log(a)
}
console.log(a)  // 결과 : 3
name()  // 결과 : 20
console.log(a) // 결과 3
</script>

 

 

<script>
// 변수 유효범위(Variable Scope)
 
function name() {
    if (true) {
        let a = 20  // let 은 블럭 레벨 범위안에서 유효
    }
    console.log(a) // 블럭 레벨 범위 밖에 a 변수
}
 
name()  // 결과 : ReferenceError: a is not defined
 
</script>

 

형변환(Type conversion)

Falsy(거짓과 같은 값) : false, '', null, undefined, 0, -0, NaN

Truthy(참과 같은 값) : true, 'false', 1, 2, -12, ....

 

NaN (Not a Number) → 1 + undefined

 

블로그 이미지

Link2Me

,