TIL 47 (2020.09.20) Bitwise, Key codes, DOM

백은진·2020년 9월 20일
0

TIL (Today I Learned)

목록 보기
47/106

[The bitwise operators]

In binary system, computer recognize decimal 1 as 00000001 (seven zero and one one), and decimal 2 as 00000010.

The bitwise or | add the number before and after.
(왜냐하면, before와 after 숫자 중 어떤 자리에 한 개만 1이 있어도, 결과값에 1을 두기 때문에.)

For example, if you log the (1 | 2) to console, you can see 3.
Because 1 is 00000001, and 2 is 00000010, so that the added numbers are equals to 00000011, which is 3 in decimal number.

Otherwise, the bitwise and & check if the two number before and after are both has a number 1.

For example, if you log the (1 & 2) to console, you can see 0.
because 1 is 00000001, and 2 is 00000010, none of the number has 1 at a same point, so that the result is 00000000 which is 0 in decimal number.

The bitwise NOT operator. ~

Simply, the not operator change 1 to 0, and 0 to 1 in binary system.

여기서 신기한 점은 , ~ operator를 붙였을 때, 아래와 같이 동작하는 점이다.

~n equals -(n+1)

// 4 examples below.

alert( ~2 ); // -3, the same as -(2+1)
alert( ~1 ); // -2, the same as -(1+1)
alert( ~0 ); // -1, the same as -(0+1)
alert( ~-1 ); // 0, the same as -(-1+1)

So we can make a return which shows something is exists or not.

let str = "Widget";

if (~str.indexOf("Widget")) {
  alert( 'Found it!' ); // works
}

그리고 console.log(~4294967295);를 하면 0이 출력되는데, 그 이유를 아직은 잘 이해하지 못하겠다.

console.log(~4294967295); // 0
console.log(~4294967297); // -2
console.log(~4294967293); // 2

[String methods]

  • includes, startsWith, endsWith 는 boolean 값을 반환한다.

  • slice 에서 end index를 지정하지 않으면, 그 글의 끝 인덱스까지 출력한다.

slicesubstring 메소드는 거의 비슷하나 다른 점이 몇 가지 있다.
그 중 하나는, 시작 인덱스와 종료 인덱스를 거꾸로 지정했을 때, substring은 순서대로 지정했을 때와 같은 값을 반환하지만, slice는 빈 string을 반환하는 것이다.

let str = "stringify";

// these are same for substring
alert( str.substring(2, 6) ); // "ring"
alert( str.substring(6, 2) ); // "ring"

// ...but not for slice:
alert( str.slice(2, 6) ); // "ring" (the same)
alert( str.slice(6, 2) ); // "" (an empty string)

str.substr(start [, length]) 메소드는 반환을 원하는 length 길이를 지정할 수 있다.

let str = "stringify";
alert( str.substr(2, 4) ); // 'ring'
alert( str.substr(-4, 2) ); // ‘gi’

[Key Code]

[String 비교하기]

  1. A lowercase letter is always greater than the uppercase:

alert( 'a' > 'Z' ); // true

  1. Letters with diacritical marks are “out of order”:

alert( 'Österreich' > 'Zealand' ); // true

  1. different case letters have different codes:
// str.codePointAt(pos)
alert( "z".codePointAt(0) ); // 122
alert( "Z".codePointAt(0) ); // 90
  1. Creates a character by its numeric code :
// String.fromCodePoint(code)
alert( String.fromCodePoint(90) ); // Z

아래의 예시를 보면, 왜 a가 Z보다 큰 수의 코드를 가지고, 
왜 Letters with diacritical marks 가 다른 글자들보다 큰 수의 코드를 가지는 지 명확히 알 수 있다.

let str = '';

for (let i = 65; i <= 220; i++) {
  str += String.fromCodePoint(i);
}
alert( str );
// ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„
// ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜ

이처럼 문자가 가진 코드의 수가 다양하다 보니,
이런 수를 확인할 수 있는 메소드도 준비되어 있다.

규칙은 다음과 같다.

  • Returns a negative number if str is less than str2.
  • Returns a positive number if str is greater than str2.
  • Returns 0 if they are equivalent.
alert( 'Österreich'.localeCompare('Zealand') ); // -1

다만, 일부 문자들은 같은 코드로 취급되기도 해서 이런 점은 주의해야 한다.
(예를 들어, "a" 와 “á”는 같은 문자 및 같은 코드로 취급된다.)


위에서 본 것과 같이 문자는 2-byte codes를 통해 구현된다.

다만, 이모티콘이나 희귀한 한자 등은 2-byte codes를 2개씩 짝지어서 구현하기도 한다. (그래서 length를 재보면 2가 출력된다.)

alert( '𝒳'.length ); // 2, MATHEMATICAL SCRIPT CAPITAL X
alert( '😂'.length ); // 2, FACE WITH TEARS OF JOY
alert( '𩷶'.length ); // 2, a rare Chinese hieroglyph

[Summary]

  • There are 3 types of quotes. Backticks allow a string to span multiple lines and embed expressions ${…}.
  • Strings in JavaScript are encoded using UTF-16.
  • We can use special characters like \n and insert letters by their unicode using \u....
  • To get a character, use: [].
  • To get a substring, use: slice or substring.
  • To lowercase/uppercase a string, use: toLowerCase/toUpperCase.
  • To look for a substring, use: indexOf, or includes/startsWith/endsWith for simple checks.
  • To compare strings according to the language, use: localeCompare, otherwise they are compared by character codes.
    There are several other helpful methods in strings:
  • str.trim() – removes (“trims”) spaces from the beginning and end of the string.
  • str.repeat(n) – repeats the string n times.
  • …and more to be found in the manual.

Strings also have methods for doing search/replace with regular expressions.
But that’s big topic, so it’s explained in a separate tutorial section Regular expressions.


[DOM!!]

Replit 에서 DOM 과 관련한 내용을 공부했다.
분명 어려운 내용은 아닌데, 헷갈리고 개념이 정리되지 않아 문제가 까다롭게 느껴진다.

그래서 DOM lesson을 찾아봤더니, Udacity의 강의가 있었다. (이번에도 codecademy로 공부하고 싶었으나, 그곳에는 준비된 코스가 없었다.)

우선, 그동안 계속 공부한 내용이지만, 다시 한 번 짚고 넘어갈 부분이 있다.
웹사이트를 동적으로 만들기 위해 JavaScript가 세상에 나왔고, 이제는 없어서는 안 될 웹사이트의 필수언어가 되었다.
따라서 HTML, CSS, JavaScript를 연결하는 API를 만드는 것이 중요한데, 그게 바로 DOM(Document Object Model)이다.

알고 있어야 할 개념

  • node: a point at which two lines or systems meet or cross.
  • html 파일에서 head 태그 내에 meta tag, link tag 등이 작성되고, body 태그 내에 p tag, div tag 등이 작성된다. 이 때 각 태그는 node이다. 부모 태그와 연결되어 있고, 자신도 새로운 자식 태그를 가질 수 있어서 중심(자신의 부모태그와 자식태그를 연결하는)이 되기 때문이다.
  • 따라서, 모든 토큰들(= 요소들)을 볼 때, 나무처럼 가지가 뻗어나간 구조를 통해 content와 property가 구성되었는데, 이러한 HTML 노드들 사이의 관계를 DOM이라고 한다.
  • 즉, DOM은 HTML markup의 전체적인 분석 표현이다.

브라우저는 서버에서 보내주는 bytes를 받아 태그로 전환하고, 그 태그들을 읽으며 토큰 리스트를 출력한다.

이 토큰 리스트가 나무 구조를 통과해 나온 아웃풋이 바로 DOM이다.
다시 말해, HTML을 전체적으로 분석한 표현이 DOM이다.

  • HTML is received
  • HTML tags are converted to tokens
  • Tokens are converted to Nodes
  • Nodes are converted to the DOM

After parsing has occurred (from the server bytes), a process called tokenization begins. Tokenization takes one character at a time and builds up tokens.

The tokens are:

  • DOCTYPE
  • start tag
  • end tag
  • comment
  • character
  • end-of-file

[document]

콘솔에 document 를 입력하면, 웹브라우저의 문서 정보가 나타난다.
그러나 document는 javascript 언어가 아니다.

In addition to the properties defined in this specification the global object may have additional host defined properties. This may include a property whose value is the global object itself; for example, in the HTML document object model the window property of the global object is the global object itself. (source)

즉, document 오브젝트는 자바스크립트가 아니지만, 이미 존재하고 있고 자바스크립트 코드와 자유롭게 연결될 수 있는 객체인 것이다.

이 사이트에 DOM에 대한 설명이 잘 정리되어 있으니, 헷갈리면 꼭 참고하자.


[DOM 개념]

DOM defines a platform-neutral model for events, aborting activities, and node trees.

Udacity는 한 강의가 끝나면 꼭 개념을 설명하거나 소감을 쓰도록 한다.

그래서 “Ok, so do not scroll back up or review what you just read. Just take a moment, think about everything you've learned about the DOM and the document object and, in your own words, write an explanation of what "the DOM" is.”라고 한 질문에 대해 아래와 같이 답했다.

The DOM is a model of document object, which used for connecting javascript with html and css.
The document object is that existing to freely connect between javascript and html, however it is not a part of javascript
.

So I think the DOM has kind of a role of API which is connecting bytes from server and Front-end sources( which is javascript, html, and css.)

맞는 답인지는 모르겠지만, 내가 이 수업을 듣고 DOM에 이해한 바는 위와 같다. 계속 공부해나갈거니까 혹시 틀리면 나중에 대조해보고 다시 공부하면 된다.

[Summary]

The DOM stands for "Document Object Model" and is a tree-like structure that is a representation of the HTML document, the relationship between elements, and contains the content and properties of the elements.

The DOM is not:

  • part of the JavaScript language

The DOM is:

  • constructed from the browser
  • is globally accessible by JavaScript code using the document object

[Getting elements]

[Select an Element By ID]

.getElementById('footer') method

: 이 메소드 자체가 아이디로 요소를 찾는 기능을 갖고 있기 때문에, css 에서 아이디를 #footer로 부르는 것처럼 하지 않고, 그냥 아이디명만 괄호 내에 적어주면 된다.

mozilla 사이트에서 consoel에 document.getElementById('content');을 logging 했더니, <div id=“content” class=“article text-content”>…</div>가 출력되었고, 맨 왼쪽의 삼각형 아이콘을 누르니, devtools-elements에서 보는 것처럼 모든 contenct div 요소들이 나타났다.

document 객체를 통해 트리 구조 전체를 관통하면서, 아이디가 content인 요소를 찾아낸 것이다.

주의!
만약 없는 ID값을 getElementById() 괄호 내에 넣어 입력한다면, null 이 return 된다.

추가+
변수에 함수를 담아 재사용을 편하게 할 수 있는 것처럼,
변수에 document.~~를 담아 재사용을 편하게 할 수 있다.


[Selecting Multiple Elements At Once]

.getElementsByClassName()
.getElementsByTagName()

주의!
multiple elements를 선택하는 메소드는 Elements
=> s 가 들어가고,
아이디 값으로 하나의 element를 선택하는 메소드는 Element
=> s 가 들어가지 않는다.

위와 같이 document.getElementsBy~~(); 코드가 바로 DOM code다.

이처럼 여러 개의 요소를 부르면, 대괄호 내에 요소들이 출력된다.
그래서 이게 배열처럼 보이기는 하지만 실제 배열 타입은 아니다.
이 정보의 prototype은 HTMLCollection이기 때문이다.


[Node]

characters(tags) -> token -> nodes -> DOM

what is a “node” exactly?

Node는 Class, node는 object같은 개념이다.

비유를 해보자면,

Node는 건물의 도면같은 것이다. (이것을 Interface라고도 한다.)
이 도면은 건물을 세우는 것과 관련한 정보를 담고 있는데, 그것을 Properties라고 한다.

반면, 건물의 기능과 관련한 정보를 담고 있는 것을 Methods라고 한다.

세부적인 예를 들자면, Properties는 건물의 색상, 문이나 창문의 수를 담고 있고, Methods는 건물의 알람 시스템이나 스프링클러 시스템을 담고 있다.

node는 Node를 통해 세워진 실제 건물(objects)를 이른다.

즉, Node Interface는 properties와 methods를 담은 것이고, 모든 실제 node들은 생성된 후 Node (기능)을 갖게 된다.


[Element Interface]

Node Interface처럼 Element Interface도 element를 만들기 위한 도면이다.

Element Interface에서 중요한 점은, 이것이 Node Interface를 세습한 것이라는 점이다.

Element Interface는 Node Interface의 properties와 methods를 모두 세습한다.

이 말인 즉슨, Element Interface로부터 생성된 모든 element는 Node Interface의 후손이라는 뜻이다.

devtools - element에서 어떤 줄을 클릭하고, console에 $0을 입력하면, 내가 element에서 클릭한 그 줄의 정보가 나타난다.
(선택한 때가 최신을 수록 0이 부여되고, 1, 2, 3, 4 등 점점 순서가 밀려난다.)

이 점을 이용해서 $0.hasAttribute(‘class’) 등을 입력해봤다.

(Element.hasAttribute()는 Element Interface의 method로 괄호 안에 입력된 요소가 있는지를 boolean으로 출력해준다. )

.getElementsByClassName() 메소드는 document 객체 뿐만 아니라 Element 객체에도 있다.

이 점을 이용해 아래처럼 원하는 요소를 변수에 넣어서 재사용을 쉽게 할 수 있다!!

// selects the DOM element with an ID of "sidebar"
const sidebarElement = document.getElementById('sidebar');

// searches within the "sidebar" element for any elements with a class of "sub-heading"
const subHeadingList = sidebarElement.getElementsByClassName('sub-heading');

[Summary]

An interface is like a blueprint,
properties are like bits of information or data,
and methods are functionality.

  • Node Interface
  • Element Interface
    We saw that both of these interfaces have properties and methods. We also saw how the Element Interface inherits all of the properties and methods from the Node interface.

Check Web APIs lists !


[JQuery]

querySelector Method를 이용해서도 ID, Class, Tag name을 뽑아올 수 있다.

// find and return the element with an ID of "header"
document.querySelector('#header');

// find and return the first element with the class "header"
document.querySelector('.header');

// find and return the first <header> element
document.querySelector('header');

주의!
.qeurySelector()는 한 개의 요소만 return 한다.

.querySelectorAll() 을 사용할 때,
1) 어떤 태그의 클래스 이름이 articles이고,
2) 나는 그 태그의 자식 태그들 중 <p>태그만 찾고 싶을 때,
아래와 같이 코드를 쓴다.

document.querySelectorAll('.articles p');

또한, .qeurySelectorAll()NodeList를 return 한다.
NodeList에 for 문이나 .forEach() 메소드를 사용할 수 있어서 아래처럼 코드를 짤 수도 있다.

const allHeaders = document.querySelectorAll('header');

for(let i = 0; i < allHeaders.length; i++){
    console.dir(allHeaders[i]);
}
profile
💡 Software Engineer - F.E

0개의 댓글