1. 자바스크립트에서  ==., ===



==는 loose equality할때 사용한다. 또한 ==은 형변환을 수행한다.

형변환 후에 오직 두개의 값 비교만 수행한다는 의미이다.

(Type coercion means that two values are compared only after attempting to convert them into a common type.)


===는 strict equality 할때 사용한다.

타입(type)과 값(value) 모두 비교했을때 같아야 한다.




2. === 비교


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Triple Equals
 
5 === 5 
// true
 
'hello world' === 'hello world'
// true (Both Strings, equal values)
 
true === true
// true (Both Booleans, equal values)
 
 
77 === '77'
// false (Number v. String)
 
'cat' === 'dog'
// false (Both are Strings, but have different values)
 
false === 0
// false (Different type and different value)
cs

type, value가 모두 같아야 true를 
둘 중 하나라도 다르다면 false를 반환하는 것을 확인할 수 있다.



3. == 비교


1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Double equals
 
77 === '77'
// false (Number v. String)
 
 
77 == '77'
// true
 
false === 0
// false (Different type and different value)
 
false == 0
// true
cs


자바스크립트는 실제로 같은 타입으로 변환을 시도하여 형변환한다. 
77 == '77' 에서 '77'은 number value로 쉽게 변환되어 true를 return 한다.


4. Falsy Value Comparison(거짓값 비교)


거짓값은 false, 0, "", null, undefined, NaN으로 총 6가지이다.

1. false — boolean false
2. 0 — number zero
3. “” — empty string
4. null
5. undefined
6. NaN — Not A Number



1. false, 0, and ""

1
2
3
4
5
6
7
8
false == 0
// true
 
0 == ""
// true
 
"" == false
// true
cs


2. null and undefined

1
2
3
4
5
6
7
8
null == null
// true
 
undefined == undefined
// true
 
null == undefined
// true
cs


3. NaN

1
2
3
4
5
6
7
8
NaN == null
// false
 
NaN == undefined
// false
 
NaN == NaN
// false
cs



5. 테스팅 코드




Triple Equals는 double equals보다 우수하다.
가능하면 테스트를 위해 비교가 필요한 구문이 필요하다면 ===를 사용하는 것이 좋다.
type과 value를 테스트해서 강제형변환을 막아 오류를 막을 수 있다.


'전체 > JS & Jquery' 카테고리의 다른 글

JS 표현식(expressions)  (0) 2019.04.09
JS scope from function, collision avoidance  (0) 2019.04.09
JS Implicit Coercion(형변환)  (0) 2019.04.08
js value와 reference  (0) 2019.03.12
js primitive type  (0) 2019.03.10


1. Implicit Coercion 



1.1 number와 string


1
2
3
4
5
6
7
8
9
10
11
3 * "3" //9
1 + "2" + 1 //121
 
true + true //2
10 - true //9
 
 
const foo = {
  valueOf: () => 2
}
3 + foo // 5
cs



숫자(number)+문자(string)는 string이 number로 변환된다.

숫자(number)+문자(string)+숫자(number)는 string로 변환된다.


true 는 numbre 1로 변환된다.

const 상수 number 로 변환된다.




1.2 number와 array


1
2
3
4
5
6
7
8
9
4 * [] // 0
 
4 * [2// 8
 
4 + [2// "42"
 
4 + [12// "41,2"
 
4 * [12// NaN
cs



number * array[0] = number

number + array[0] = string

number + array[0,1] = string

number * array[0,1] = NaN




3. string to number


1
2
3
4
5
6
7
8
9
10
11
12
13
14
3 * "3" // 3 * 3
3 * Number("3"// 3 * 3
Number("5"// 5
 
Number("1."// 1
Number("1.34"// 1.34
Number("0"// 0
Number("012"// 12
 
Number("1,"// NaN
Number("1+1"// NaN
Number("1a"// NaN
Number("one"// NaN
Number("text"// NaN
cs



String to Number일때 Implicit Coercion NaN이 발생한다.




4. typeof


1
2
3
4
5
const add = (number) => {
  if (typeof number !== "number"new Error("Only accepts arguments of type: number")
  //your code
  else return number;
}
cs



type check -> error or return value 




2. 테스트 소스





자바스크립트에서 string, number, string to number로 강제형변환이 일어나는 것을 확인할 수 있었다.


'전체 > JS & Jquery' 카테고리의 다른 글

JS scope from function, collision avoidance  (0) 2019.04.09
JS ==, === 의 비교  (0) 2019.04.08
js value와 reference  (0) 2019.03.12
js primitive type  (0) 2019.03.10
자바스크립트 콜스택(call stack)  (0) 2019.03.09

 

1. sourcetree 도구 > 옵션 > 기본 텍스트  인코딩 확인

 

- 기본 텍스트 인코딩을 euc-kr 이나 utf-8로 바꿔본다.

 

2. sourcetree 설정 > 설정파일 편집 > 워드패드, notepad++ 열기

 

 

다음을 추가해준다.

 

[i18n]
  commitEncoding = UTF-8

  logOutputEncoding = UTF-8

 

[core]
  symlinks = false
  repositoryformatversion = 0
  filemode = false
  logallrefupdates = true


[remote "origin"]
  url = https://github.com/shlee0882/spring-uses.git
  fetch = +refs/heads/*:refs/remotes/origin/*

 

[branch "master"]
  remote = origin
  merge = refs/heads/master

 

 


1. imgur 사이트에서 open api 로 이미지 업로드 기능을 제공한다.


imgur api doc 사이트 접속 : https://apidocs.imgur.com/


하면 다음과 같은 사이트가 나온다.






2. API를 사용하기 위해서는 https://api.imgur.com/oauth2/addclient 경로로 들어간다.





다음 화면에서 application name, callback url, email을 작성해준다.

postman에서 사용할 callback url인 https://www.getpostman.com/oauth2/callback 을 입력해준다.


작성 후 submit을 누르면 


Client ID, Client secret을 제공해준다.





이제 계정을 테스트해봐야한다.



3. 구글에서 postman을 검색해 설치해준다.



크롬 확장프로그램이 아닌 postman application 프로그램으로 다운받아 설치한다.



4. postman을 통해 테스트 환경설정 하기



이후 Authorization 탭의 TYPE OAuth 2.0 을 선택하고 Get New Access Token을 누른다.







Callback URL :  https://www.getpostman.com/oauth2/callback 


Auth  https://api.imgur.com/oauth2/authorize


Access Token URL https://api.imgur.com/oauth2/token


Client ID : 애플리케이션 등록하며 받은 ID


Client secret : 애플리케이션 등록하며 받은 secret


입력하고 Request Token을 누른다.


그러면 imgur 로그인을 allow 할지 deny할지 물어본다.

당연히 allow하여 access하는것을 허용한다.


성공적이라면 다음과 같이 refresh_token을 제공해준다.





해당 내용을 메모장에 복사한 후 Use Token을 클릭한다.


오른족 상단 톱니바퀴를 클릭하여 add environment를 하여 환경설정에 다음과 같이 입력한다.


발급받은 refreshToken


애플리케이션 등록할때 발급받은  clientId, clientSecret


의 값을 넣어주고 환경설정을 변경해준다.







5. 테스트 Access Token 실행하기


이후 imgur API 에서 제공해주는 여러 테스트 코드의 Account > Generate Access Token을 실행해본다.

POST방식으로 send를 보내면 결과값이 잘 나타난것을 확인할 수 있다.






6. 업로드 해보기


위에 과정이 성공적으로 나타났다면 이미지 업로드를 해볼차례이다.


다음과 같은 index.html 파일을 생성한다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!DOCTYPE html>
<html>
<head>
    <script
  src="https://code.jquery.com/jquery-3.3.1.js"
  integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
  crossorigin="anonymous"></script>
</head>
<body>
    <button id="upload">upload image</button>
    <script type="text/javascript">
 
    $( document ).ready(function() {
        var form = new FormData();
        form.append("image""https://avatars0.githubusercontent.com/u/9919?s=280&v=4");
 
        var settings = {
          "url""https://api.imgur.com/3/image",
          "method""POST",
          "timeout"0,
          "headers": {
            "Authorization""Client-ID c1934aa57a01a08"
          },
          "processData"false,
          "mimeType""multipart/form-data",
          "contentType"false,
          "data": form
        };
 
        $("#upload").click(function() {
            $.ajax(settings).done(function (response) {
              console.log(response);
              alert(response);
            });
        });
    });
    </script>
</body>
</html>
cs



버튼을 눌렀을때 이미지를 imgur api 를 사용해 이미지 웹서버로 전송한다.

현재 이 코드에서 필요한 것은 


1. A binary file, base64 data, or a URL for an image (up to 10MB)

2. Client-ID 이다.


ajax 통신을 통해 image 정보와, client id를 넣어 data를 보내면 response로 json을 반환한다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
{
  "data": {
    "id": "lnX1JMq",
    "title": null,
    "description": null,
    "datetime": 1553655107,
    "type": "image/png",
    "animated": false,
    "width": 280,
    "height": 280,
    "size": 13959,
    "views": 0,
    "bandwidth": 0,
    "vote": null,
    "favorite": false,
    "nsfw": null,
    "section": null,
    "account_url": null,
    "account_id": 0,
    "is_ad": false,
    "in_most_viral": false,
    "has_sound": false,
    "tags": [],
    "ad_type": 0,
    "ad_url": "",
    "edited": "0",
    "in_gallery": false,
    "deletehash": "HQF1cQmsRB1lHsa",
    "name": "",
    "link": "https://i.imgur.com/lnX1JMq.png"
  },
  "success": true,
  "status": 200
}
cs



반환한 데이터의 업로드된 이미지 url로 접속하면


https://i.imgur.com/lnX1JMq.png


업로드가 잘 된 것을 확인 할 수 있다.




1. Value





1
2
3
4
let a = 10;
let b = a;
= 20;
console.log(b);
cs


a는 10이고 a의 값을 b에 주입하여 10이 되었다.

(a값을 복사해서 b에 붙여넣음)


그래서 아래 a의 값을 20으로 변경해도 b는 값의 영향을 벗어난다.

이것을 value라고 한다.


value는 string number, boolean, NaN, undefined, null 가능하다.



2. Reference






1
2
3
4
const a = ["apple","banana"]
const b = a;
a.push("carrot");
console.log(b);
cs


b에는 ["apple", "banana", "carrot"] 가 들어있다.

레퍼런싱하는 것이다. 배열을 참조 하고 있는 것이다.

a와 b가 가르키는 배열은 메모리 어딘가에 위치해있고 동일한 배열을 바라보고 참조하는 것이다.





1
2
3
4
const a = { x: 'hi'}
= a;
b.x = 'hello';
console.log(a);
cs


마찬가지로 map 형식의 데이터도 레퍼런스 참조를 하는 것을 확인할 수 있다.


reference는 arrray, object, function 에서 사용될수 있다.




자바스크립트 primitive type



1. string, number, boolean 비교








2. undefined, null, NaN 비교






 항목

 내용 

 undefined

 정의되지 않음,

 null

 존재하지 않음

 NaN(Not a Number)

 계산이 잘못됨 wrong result




자바스크립트 콜스택(call stack)



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function four(){
 console.log("four function execute");
}
 
function three(){
    four();
}
 
function two(){
  three();
}
 
function one(){
  two();  
}
 
one();
cs



다음과 같이 javascript에

one() 이라는 함수를 실행하면 two()를 부르고 

two()는 three()를 부르고, three()는 four()를 불러서 

console.log("four function execute")를 찍는다.


자바스크립트는 함수를 스택 위에 올리고 



 

 

 

 four() 

 

 

 three() 

 three() 

 

 two()

 two()

 two()

 one()

 one()

 one()

 one()



함수를 다 실행하면 하나씩 pop하면서 제거한다.



 four()

 

 

 

 three() 

 three() 

 


 two()

 two()

 two()


 one()

 one()

 one()

 one()


스택을 다 처리하면 실행시킬 것이 없는 거다.

실행이 완료되면 함수는 리스트에서 사라진다.




만약 스택에 올라가있는 함수에 

다음과 같은 throw 에러문이 있다면


1
throw Error("i am an error");
cs


에러 전에 있던 있던 모든 콜스택을 알려준다.





또한 스택에 함수를 계속 호출한다면 스택에 계속 쌓이게 되고 

스택의 사이즈는 한계가 있으므로 다음과 같은 오류가 발생한다.






1. callstack.html


1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html>
<head>
  <title>js 콜스택 테스트</title>
  <meta charset="utf-8" />
</head>
<body>
  <script type="text/javascript" src="callstack.js"></script>
  <h1>Hello</h1>
  <div>
  </div>
</body>
</html>
cs



2. callstack.js


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function four(){
 console.log("four function execute");
}
 
function three(){
    four();
}
 
function two(){
  three();
}
 
function one(){
  two();  
}
 
one();
cs



3. 실행결과 및 동작원리






자바스크립트는 함수를 스택 위에 올리고 함수가 실행되고 끝이 나면 pop하여 없애는 것을 확인할 수 있었다.




 AWS RDB에 테이블 생성 후


테이블의 한글 데이터를 넣으려고 하면 한글이 ?? 로 들어가는 경우가 있다.


해당문제는 charset의 인코딩 문제여서


1. AWS RDB에 연결된 파라미터 그룹의 charset을 utf8로 바꿔주고 

인스턴스 db를 재시작하는 것도 방법이지만






2. 해당 테이블의 char-set을 utf8로 바꿔주는 것도 방법이 될수 있다.



1
ALTER TABLE 테이블명 CONVERT TO character SET utf8;
cs




+ Recent posts