0% found this document useful (0 votes)
12 views11 pages

Môn JS

The document provides a comprehensive overview of various programming concepts and techniques, including DOM manipulation, event handling, sorting data, and working with classes and promises in JavaScript. It covers practical examples such as selecting options, handling date inputs, and using JSON. Additionally, it discusses the structure and usage of functions, arrays, and asynchronous operations, making it a valuable resource for developers looking to enhance their coding skills.

Uploaded by

antu12666
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views11 pages

Môn JS

The document provides a comprehensive overview of various programming concepts and techniques, including DOM manipulation, event handling, sorting data, and working with classes and promises in JavaScript. It covers practical examples such as selecting options, handling date inputs, and using JSON. Additionally, it discusses the structure and usage of functions, arrays, and asynchronous operations, making it a valuable resource for developers looking to enhance their coding skills.

Uploaded by

antu12666
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Contents

DOM Chọn phần tử.....................................................................................................................................1


sort date......................................................................................................................................................2
Hàm sự kiện.................................................................................................................................................2
Vòng lặp.......................................................................................................................................................2
Làm việc với select option...........................................................................................................................4
onChange....................................................................................................................................................4
Ngày tháng..................................................................................................................................................4
class.............................................................................................................................................................5
promise.......................................................................................................................................................8
touch event.................................................................................................................................................9
oninput........................................................................................................................................................9
get attribute..............................................................................................................................................10
querySelector............................................................................................................................................10
innerHTML.................................................................................................................................................10
Làm việc với mảng.....................................................................................................................................10
function.....................................................................................................................................................10
JSON..........................................................................................................................................................11

DOM Chọn phần tử


.parentElement

.children[i]

.removeChild

remove() là xóa phần tử con nên nếu phần tử cần xóa không phải con thì sẽ lỗi

document.getElementById("tbody/pt
cha").removeChild(document.getElementById(pt con));

parentNode
childNodes[nodenumber]

firstChild

lastChild

nextSibling

previousSibling

sort date
const latestMovies = moviesWithReleaseDate

.sort((a, b) => {

return moment(a.release_date).diff(b.release_date);

})

.reverse()

.slice(0, 20);

Hàm sự kiện
REACT:

*{()=>tenHam()} //tenHam(e)

*={tenHam} (thường khi có dùng tới e.target.value)

*={tenHam()}

Vòng lặp
*oj trong oj => dùng thuộc tính của oj bao ngoài => dùng for in

VD:

const newArr = [];


for(let key in data){

newArr.push({

id: key,

title: data[key].title,

date: data[key].date

});

BE Chia nhỏ kết quả trả về cho FE

//trả về danh sách các film được sắp xếp theo trường popularity giảm dần

const sortedMovieList = movieList.sort((a, b) => b.popularity - a.popularity);

//mỗi Page sẽ chứa 20 phần tử

const paginate = (array, page_size, page_number) => {

// human-readable page numbers usually start with 1, so we reduce 1 in the


first argument

return array.slice((page_number - 1) * page_size, page_number * page_size);

};

const movieList20ItemsPerPage = paginate(

sortedMovieList,

20,

req.params.page ? req.params.page : 1

);
_

return res.status(200).json({

results: movieList20ItemsPerPage,

page: req.params.page ? req.params.page : 1,

total_pages: Math.ceil((movieList.length - 1) / 20),

})

Làm việc với select option


VD1:

<select value={yearSelected} id="selectyear" onChange={selectYear}>

{props.years

.sort((a, b) => b - a)

.map((year) => (

<option key={Math.random() * 5} value={year}>

{year}

</option>

))}

</select>

onChange
*get e.target

onChange={()=>selectYear()}

=> onChange={selectYear}
Ngày tháng
*Lấy tháng, dạng chữ, tiếng Anh thì "en-US", nếu để "default" thường là tiếng Việt

date.toLocaleString("en-US", { month: "long" })

*Date Picker

https://www.npmjs.com/package/react-date-range

import { DateRange } from "react-date-range";

<DateRange

editableDateInputs={true}

moveRangeOnFirstSelection={false}

className="date"

minDate={new Date()}

onChange={...}

ranges={...}

/>

class
as we code complex programs, we'll need to create many similar but distinct
objects. For example, all the books in the library.

But creating a new object for thousands of books would take a lot of time and
could lead to errors.

To make this process less error-prone and more efficient, we can use data
structures called classes as templates. Once we create a template with the
properties we'll want for all similar objects, we can use it to create new objects
faster.
To create new objects, classes need a special method called the constructor().
This method sets the property values for a new object.

We add the this keyword to refer to the object being created.

Adding a method in a class is like creating a regular function, except there's no


need for the function keyword.

Every time we create an oj from a class, we're creating what's called an instance
of that class.

Vd: class Book {

constructor(author, title){

this.author: author;

this.title: title

read(){}

const book1 = new Book("string1", "string2");

book1.read();

because instances are independent, they let us keep track of complicated date
like a huge number of users on a website. In this example, we keep track of four
users and whether they're online. A real website might keep track of hundreds.

class User{

constructor(name){

this.name = name;

this.isOnline = true;
this.preiods = 4;

const user1 = new User("string");

const user2 = new User("string");

const user3 = new User("string");

const user4 = new User("string");

const user5 = new User("string");

the constructor() can be empty. Contructors are so essential for classes that a
default constructor is created even if we don't add it.

Imagine we're making a zoo game. The animals in the zpp have a lot in common,
but they're also different in many ways. That's where inheritance comes into play.

Vd: class Dog extends Animal {} => inheritance gives a class all the properties and
methods of the class it's extending or inhering from. Here, Dog is a subclass of the
Animal class. The Animal class, then, is its superclass.

If a subclass doesn't have a constructor() method, the superclass' contructor


becomes the default constructor.

Vd: class Animal {

constructor(name){

this.name = name;

class Dog extends Animal {}


const dog = new Dog("Pug");

console.log(dog.name);

lấy phương thức từ class có chọn lọc và thêm thắt mới, thì dùng super

vd: class Wizard extends Human {

attack(){

super.attack(); chép cũ, đã có trước đó

console.log( thêm mới, cái riêng

tương tự khi muốn chép properties => dùng super() trong constructor {}

promise
promises are objects that represent the outcome of an asynchronous operation. It
can be fulfilled or rejected. When we're waiting to know the result, the promise is
pending. To create a new Promise oj, we use the new keyword and the Promise
constructor method. The constructor takes a function as a parameter. The
passed-in function itself taskes two parameters. The first is resolve and the
second is reject.

Vd: const promiseDemo = new Promise (function(resolve, reject){});

The promise constructor passes its own resolve and reject functions into the
constructor. If the promise if fulfilled, the resolve function changes the promise
status from pending to fulfilled. The resolve function takes one argument.

Vd: function orderCheeseCake(){

return new

Promise(function(resolve, reject){

if(dessertStock, cheeseCake > 0){

resolve("Cheesecake is available in the stock. Order has been processed.");}});}


const makeOrder = orderCheeseCake();

console.log(makeOrder);

->Promise{' Cheesecake is available in the stock. Order has been processed.'}

Once a promise is resolved, we need to handle the resolved or rejected data. =>
we use .then to include actions for when the promise is no longer in the pending
state.

Vd: const makeOrder = orderCheeseCake();

makeOrder.then(function(successValue){console.log

successValue is the value return when the promise resolves

what if the promise is not fulfilled? The .then method won't execute and we'll get
an uncaught error. To sort this out, we can use the .catch method to handle
errors when the promise is rejected

vd: .catch(function(failureValue)

async function always returns promise objects.

Await waits for the promise to be resolved. Await pauses the execution of async
code inside the asyncFunction until createNewPromiseFunction is resolved

touch event
.addEvenListener("touchstart",) chạm

.addEvenListener("touchmove",) lướt

.addEvenListener("touchend",) thả tay

.addEvenListener("touchcancel",) khi bị gián đoạn => gọi hàm liên quan đến error

oninput
const input = document.querySelector('input');
const log = document.getElementById('log');

function undateValue() {

log.innerText = input.value.length + "characters";}

input.oninput = updateValue;

get attribute
by a .

vd: el.style.backgroundColor = "red"

by using .getAttribute("src")

=> set or update attribute: .setAttribute("attribute", value)

querySelector
collections are similar to arrays. They work with indices that start from 0

vd: const el = document.querySelector('p');

el[0] -> the first p

innerHTML
tableBodyEl.innerHTML = ""

innerText: Hello 2020 => span

textContent: Hello

Làm việc với mảng


*let abc = toDo.pop() -> lưu phần tử

*yearArr = expensesYear.filter((year) => yearArr.includes(year) ? "" :


yearArr.push(year)
*sắp xếp: .sort((a,b)=>a-b)

function
đặt tên: động từ, vd sumTotal (các hàm tương tự nhau thì động từ phía trước
cũng nên giống nhau), hoặc isFreezing (với giá trị boolean)

JSON
We can create jsonVariable like a regular oj {} but wrapped with single quotes '

Cannot store functions inside

vd: const jsonString = '{"story": "Life"}'

You might also like