본문 바로가기

webOS

# JavaScript

 

JavaScript 공부한 내용 올립니다.(계속 추가할 예정)


JavaScript

Comments: // or /* */

Data type

  • boolean – true / false
  • null
  • undefined
  • number
  • string
  • symbol

 

variables

 
var
Variable
let
Block variable(cannot be redeclared)
const
Block constant(cannot be reassigned)

 

arithmetic operator

 
+
Addition
-
Subtraction
*
Multiplication
**
Exponentiation
/
Division
%
Modulus(remainder)
++
Increment
--
decrement

 

Comparison operator

 
==
Equal to
===
Equal value and equal type
!=
Not equal
!==
Not equal or not equal type
>
Greater than
<
Less than
>=
Greater than or equal to
<=
Less than or equal to
?
Ternary operator

 

Logical operator

 
&&
Logical and
||
Logical or
!
Logical not

 

Bitwise operator

 
&
AND
|
OR
~
NOT
^
XOR
<<
Left shift
>>
Right shift
>>>
Unsigned right shift

 

Type operator

 
typeof
Returns the type of a variable
instanceof
Returns true if an object is an instance

 

Conditional statements

1. if / else if / else

if (표현식1) {
    표현식1의 결과가 참일 때 실행하고자 하는 실행문;
} else if (표현식2) {
    표현식2의 결과가 참일 때 실행하고자 하는 실행문;
} else {
    표현식1의 결과도 거짓이고, 표현식2의 결과도 거짓일 때 실행하고자 하는 실행문;
}
 

 

2. switch

 

switch (조건 값) {
    case 값1:
        조건 값이 값1일 때 실행하고자 하는 실행문;
        break;
    case 값2:
        조건 값이 값2일 때 실행하고자 하는 실행문;
        break;
    ...
    default:
        조건 값이 어떠한 case 절에도 해당하지 않을 때 실행하고자 하는 실행문;
        break;
}
 

 

iterative statements

1. while

while (표현식) {
    표현식의 결과가 참인 동안 반복적으로 실행하고자 하는 실행문;
}
 

 

2. do / while

do {
    표현식의 결과가 참인 동안 반복적으로 실행하고자 하는 실행문;
} while (표현식);
 

 

3. for

for (초기식; 표현식; 증감식) {
    표현식의 결과가 참인 동안 반복적으로 실행하고자 하는 실행문;
}
 

 

4. for /in

for (변수 in 객체) {
    객체의 모든 열거할 수 있는 프로퍼티의 개수만큼 반복적으로 실행하고자 하는 실행문;
}
 

 

5. for / of

for (변수 of 객체) {
    객체의 모든 열거할 수 있는 프로퍼티의 개수만큼 반복적으로 실행하고자 하는 실행문;
}
 

 

 

array

1. var arr = [배열요소1, 배열요소2,...];          // 배열 리터럴을 이용하는 방법
2. var arr = Array(배열요소1, 배열요소2,...);     // Array 객체의 생성자를 이용하는 방법
3. var arr = new Array(배열요소1, 배열요소2,...); // new 연산자를 이용한 Array 객체 생성 방법

: arr.push(VALUE) / arr.pop() / arr.shift() / arr.unshift() / arr.length / arr.toString() / arr.join()

 

 

function

function 함수이름(매개변수1, 매개변수2,...) {
    함수가 호출되었을 때 실행하고자 하는 실행문;
}
 

 

ex)

// addNum라는 이름의 함수를 정의함.
function addNum(x, y) {    // x, y는 이 함수의 매개변수임.
    document.write(x + y);
}
addNum(2, 3);              // addNum() 함수에 인수로 2와 3을 전달하여 호출함.
 

 

object

var 객체이름 = {
    프로퍼티1이름 : 프로퍼티1의값,
    프로퍼티2이름 : 프로퍼티2의값,
    ...
};
 

l  new OBJECT()

l  Object.create(프로토타입객체[, 새로운객체의프로퍼티1, 새로운객체의프로퍼티2, ...]);

 

ex)

 

var person = {
    name: "홍길동",      // 이름 프로퍼티를 정의함.
    birthday: "030219",  // 생년월일 프로퍼티를 정의함.
    pId: "1234567",      // 개인 id 프로퍼티를 정의함.
    fullId: function() { // 생년월일과 개인 id를 합쳐서 주민등록번호를 반환함.
        return this.birthday + this.pId;
    }
};
person.name    // 홍길동
person["name"] // 홍길동
 
 
object - prototype
function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
}

const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");​
 
 
promises
let promise = new Promise(function(resolve, reject) {
  // 프라미스가 만들어지면 executor 함수는 자동으로 실행됩니다.

  // 1초 뒤에 일이 성공적으로 끝났다는 신호가 전달되면서 result는 '완료'가 됩니다.
  setTimeout(() => resolve("완료"), 1000);
});


promise.then(
  result => alert(result), // 1초 후 "완료!"를 출력
  error => alert(error) // 실행되지 않음
);​

: executor – Promise 생성 시 자동 실행, 성공 여부에 따라 resolve / reject 호출

: resolve(value) – 일이 성공적으로 끝난 경우 value와 함께 호출

: reject(error) – 에러 발생 시 에러 객체

: promise state – pending -> resolve 호출 시 fulfilled / reject 호출 시 rejected

.then

promise.then(
  function(result) { /* 결과(result)를 다룹니다 */ },
  function(error) { /* 에러(error)를 다룹니다 */ }
);

: 첫번째 인수 이행 시 실행, 두번째 인수 거부 시 실행(error)

: ex)

function loadScript(src) {
  return new Promise(function(resolve, reject) {
    let script = document.createElement('script');
    script.src = src;

    script.onload = () => resolve(script);
    script.onerror = () => reject(new Error(`${src}를 불러오는 도중에 에러가 발생함`));

    document.head.append(script);
  });
}
 
: async, await
 
function loadScript(src) {
  return new Promise(function(resolve, reject) {
    let script = document.createElement('script');
    script.src = src;

    script.onload = () => resolve(script);
    script.onerror = () => reject(new Error(`${src}를 불러오는 도중에 에러가 발생함`));

    document.head.append(script);
  });
}​

: async – 함수가 promise를 반환

: await – promise가 처리될 때까지 함수가 실행되지 않고 기다림, 처리되면 실행 재개


Web API

mediaDevices

The mediaDevices interface provides access to connected media input devices like camera and microphones, as well as screen sharing. In essence, it lets you obtain access to any hardware source of media data.

 
mediaDevices.getUserMedia()
Provides permission to use a media input
Returns a Promise resolves to a mediaStream
mediaDevices.enumerateDevices()
Requests a list of the available media input and output.
 
 

 

mediaStream

The mediaStream interface represents a stream of media content. A stream consists of several tracks, such as video or audio tracks.

 

Navigator

The navigator interface represents the state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities.

 
navigator.mediaDevices
Returns a MediaDevices object
 
 

 

Window

The window interface represents a window containing a DOM document; the document property points to the DOM document loaded in the window.

window.location Returns a location object
   
   

 

Location

The location interface represents the url of the object it is linked to. Both Document and Window interface have such a linked location, accessible via document.location and window.location respectively.

Location.origin Returns protocol + domain + port

 

 

HTML DOM

HTML DOM events

: Events are normally used in combination with functions, and the function will not be executed before the event occurs. When JavaScript is used in HTML pages, JavaScript can "react" on these events. HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

 
onclick
The user clicks an HTML element
onchange
An HTML elements has been changed
onmouseover
The user moves the mouse over an HTML element
onmouseout
The user moves the mouse away from an HTML element
onkeydown
The user pushes a keyboard key
onload
The browser has finished loading the page
onsubmit
Occurs when a form is submitted

 

Document object: When an HTML is loaded into a web browser, it becomes a document object. If you want to access any element in an HTML page, you always start with accessing the document object.

 
document.write(TEXT)
Write into the HTML output stream
document.getElementById(ID)
Returns an element with specific value
document.querySelector(CSS_selectors)
Returns the first object matches a CSS selector
document.querySelectorAll(CSS_selectors)
Returns NodeList that matches a CSS selector
 
 
 
 

 

Style object

 
OBJECT.style.backgroundColor = COLOR
Sets or returns the background color
OBJECT.style.color = COLOR
Sets or returns the color of the text???
 
 
 
 

 


 

'webOS' 카테고리의 다른 글

webOS: web app 개발일지(2)  (0) 2022.09.28
webOS: web app 개발일지(1)  (0) 2022.09.19
# CSS  (0) 2022.08.23
# HTML  (0) 2022.08.23
webOS(4): target device 설정과 sample web app 제작  (0) 2022.07.31