--------------- <> -----------------
--- KHOA HỌC - CÔNG NGHỆ - GIÁO DỤC - VIỆC LÀM ---
--- Học để đi cùng bà con trên thế giới ---

Tìm kiếm trong Blog

Hiển thị các bài đăng có nhãn Javascript. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn Javascript. Hiển thị tất cả bài đăng

Làm web (js05) - JS: Objects

Bài trước: Làm web (js04) - JS: Functions
----------

5         Objects


Everything in JavaScript is either one of the six primitive data types (strings, numbers, booleans, symbols, undefined, and null) or an object. We’ve actually met some objects already, those are arrays and functions. However, they are almost built-in objects. In this chapter we’re going to look at user-defined objects, as well as some of the other built-in objects.

In this chapter, we’ll cover the following topics:

– Object literals

– Adding properties to objects

– Object methods

– JSON

– The Math object

– The Date object

– The RegExp object

– Project: we’ll create quiz and question objects and ask random questions

5.1       Object literals (p167)


An object in JavaScript is a self-contained set of related values and functions. They act as a collection of named properties that map to any JavaScript value such as strings, numbers, booleans, arrays and functions. If a property’s value is a function, it is known as a method.

One way to think about a object is that it’s like a dictionary where you look up a property name and see a value.

Objects are often used to keep any related information and functionality together in the same place.

5.2       Creating objects (p169)


const spiderman = {};

or,

const spiderman = new Object();

Accessing properties (p170)

You can access the properties of an object using the dot notation.

You can also access an object’s properties using bracket notation–the property is represented by a string inside square brackets, so needs to be placed inside single or double quotation marks.

Computed properties (p171)

Example using operator + to concatenate the strings:

const hulk = { name: 'Hulk', ['catch' + 'Phrase']: 'Hulk Smask!' };
console.log(hulk);
//> {name: "Hulk", catchPhrase: "Hulk Smask!"}

Example using ternary operator:

const bewitched = true;
const captainBritain = { name: 'Captain Britain', hero: bewitched ? false : true };
console.log(captainBritain);
//>{name: "Captain Britain", hero: false}

The new Symbol type can also be used as a computed property key:

const name = Symbol('name');
const supergirl = { [name]: 'Supergirl' };
console.log(supergirl);
//> {Symbol(name): "Supergirl"}

A new property can be added to an object using a symbol as a key if the square bracket notation is used:

Calling methods (p172)

To call an object’s method we can also use dot or bracket notation.

Checking if properties or methods exist (p173)

const ob = {
    name: 'Teo',
    weight: 60,
 fly() {
        console.log('fly');
    }
};

console.log('name' in ob);

Another example,

student = {
    name: 'Teo',
    age: 20,
    greeting(){
        alert(`Hi, My name is ${this.ten}.`);
    }
}
console.log('name' in student);
console.log(student.hasOwnProperty('name'));

Finding all the properties of an object (p174)

Adding properties (p176)

Changing properties (p177)

Removing properties (p177)

5.3       Nested objects (p178)


Objects as a parameters to functions (p180)

This (p181)

Namespacing (p182)

5.4       Built-in objects


JSON (p184)

Math (p186)

Date (p196)

Lab 17. As you’ve known, timestamp is a value that represents the number of milliseconds since 01/01/2070. Let’s find the timestamp so that when you run chunk of following code, the result will be 02/01/1970.
const result = new Date(timestamp);
console.log(result.toString());

RegExp (p201)

A regular expression (or RegExp, for short) is a pattern that can be used to search strings for matches to the pattern. A common use is “find and replace” type operations.

Lab 18. Using https://regex101.com/ to learn RegExp.

Creating regular expression (p202)

– Using literal notation of writing the regular expression between forward slashes.

const pattern = /[a-zA-Z] + ing$/;

– Create a new instance of the RegExp object using the new operator and a constructor function

const pattern = new RegExp(‘[a-zA-Z] + ing’);

Regular methods (202)

– Using test() method to see if a string (passed to the method as as parameter) matches the regular expression pattern. It returns true if the pattern is in the string, and false if it isn’t.

Example:

  pattern.test(‘joke’);
<< false
  pattern.test(‘joking’);
<< true
  pattern.test(‘jokingly’);
<< false

Lab 19. Using prompt of JavaScript allowing user input any word, if the word is “stop” then stop program. Using RegExp to write this program.

– The exec() method works in the same way as the test() method, but instead of returning true or false, it returns an array containing the first match found, or null if there aren’t any matches:

Lab 20. Using prompt of JavaScript allowing user input their full name. Using regular expression to check if the first name is “Teo”, stop input processing and convert first name into uppercase. Output full name to console window.

Basic regular expressions (p204)

Character groups (p204)

Regular expression properties (p205)

Special characters (p207)

Modifiers (p207)

Greedy and lazy modifiers (p208)

A practical example (p209)

String methods (p210)


Quiz ninja project (p212)
-----
Cập nhật: 12/11/2019
-----

Làm web (js04) - JS: Functions

Bài trước: Làm web (js03) - JS: Arrays, Logic and Loops
----------

4         Functions


A function is a chunk of code that can be referenced by a name, and is almost like a small, self-contained mini program. Functions can help reduce repetition and make code easier to follow.

In this chapter, we’ll be covering these topics:

– Defining functions―function declarations, function expressions, Function() constructors and the new arrow syntax

– Invoking a function

– Return values

– Parameters and arguments

– Hoisting―variables and functions

– Callbacks―functions as a parameter

– Project ― we’ll be using functions to make the Quiz Ninja code easier to follow

4.1       Defining a Function (p133)


Function declarations (p133)

function hello(){
console.log('Hello World!');
}

hello();

Lab 8. Write a program using function declaration. Program allows user input a number, then output the sum from 0 to that number.

Function Expression (p134) (anonymous function)

const goodbye = function(){
console.log('Goodbye World!');
};

or,

const goodbye = function bye(){
console.log('Goodbye World!');
};
goodbye();
bye() //error

Lab 9. Write a program using function expression. Program allows user input fullname, then output the fullname as uppercase.

Every function has a name (p135)

Using when debug to know which functions are causing a problem.

console.log(goodbye.name);

Function constructor (p135)

It is not recommended to use this way to declare a function.

4.2       Invoking a function (p136)

4.3       Return Values (p137)

4.4       Parameters and arguments (p138)


Variable numbers of arguments (p140)

Lab 10. Use rest parameter to write the function that allow to get the mean of any set of number.

A sample code:

function mean(...rest){
    let total = 0;
    for(item of rest){
        total += item;
    }
    return total/rest.length;
}
console.log(mean(1,2,1,2,3,4));

Arrow function (p145)

Function hoisting (p147)

Variable hosting (p148)

Variable hoisting can cause quite a bit of confusion and also relies on using var to declare variables. An error will be thrown if you attempt to refer to a variable before it has been declared using const and let. It’s better practice to use const and let to declare any variables at the beginning of a block so hoisting is unnecessary.

4.5       Callbacks (p149)


Remember at the start of this chapter when we said that functions in JavaScript are first-class objects, so they behave in just the same way as every other object? This means that functions can also be given as a parameter to another function. A function that is passed as an argument to another is known as a callback.

Consider a function:

function sing(song) {
console.log(`I'm singing along to ${song}`);
}
sing('Let It Go')
<< 'I'm singing along to Let It Go'

We can make the sing() function more flexible by adding a callback parameter:

function sing(song,callback) {
console.log(`I'm singing along to ${song}.`);
callback();
}

The callback is provided as a parameter, then invoked inside the body of the function.
But what if the function isn’t provided as an argument?

There is nothing to actually define a parameter as a callback, so if a function isn’t provided as an argument, then this code won’t work. It is possible to check if an argument is a function using the following code:

if(typeof(callback) === 'function '){
callback();
}

This will only attempt to invoke the callback if it is a function.

Now we can create another function called dance() that can be used as the callback:

function dance(){
console.log(‘I am moving my body to the groove.’);
}

Now we can call our sing function, but we can also dance as well as sing:

sing(‘Let it go’, dance);

Lab 11. Applying callback function.

As you known, arrays have sort() method to sort all items in array. Try with this array [1,3,12,5,23,18,7].sort();

The result is [1, 12, 18, 23, 3, 5, 7], what is happened? JavaScript has converted numerical array into strings, then placed in alphabetical order.

So, write a function to sort an array based on numerical values:

function numerically(a,b){
    return (a-b)
}

This function can now be used as a callback in the sort() method to sort the array of numbers correctly.

console.log(arr.sort(numerically));
// [1, 3, 5, 7, 12, 18, 23]

Code sample:

const arr = [1,3,12,5,23,18,7];
// console.log(arr.sort());
function numerically(a,b){
    return (a-b)
}
console.log(arr.sort(numerically));

4.6       Array Iterators (p153)


Arrays have a number of methods that utilize callbacks to make them more flexible.

– forEach()

In the last chapter, you can use a for loop to loop through each value in an array like so:

const colors = ['Red', 'Green', 'Blue'];
for(let i = 0; i < colors.length; i++){
    console.log(`Color at position ${i} is ${colors[i]}`);
}

An alternative is to use the forEach() method. This will loop through the array and invoke a callback function using each value as an argument. The callback function takes three parameters, the first represents the value in the array, the second represents the current index and the third represent the array tha the callback is being called on. The example above could be written as:

colors.forEach( (color, index) =>  { console.log(`Color at position ${index} is ${color}`);});

or,

colors.forEach( (color, index) =>  {
    console.log(`Color at position ${index} is ${color}`);
});

or,

colors.forEach( (color, index) =>  console.log(`Color at position ${index} is ${color}`));

– map() (p154)

For example,

console.log([1,2,3].map( square ));
function square (x) {
    return x*x;
}
//> [1, 4, 9]

An anonymous function can also be used as a callback. This example will double all the number in the array:

console.log([1,2,3].map( x => x * 2 ));
//>[2, 4, 6]

or,

console.log([1,2,3].map( (x) => x * 2 ));

or,

console.log([1,2,3].map( (x) => {
    return x * 2;
 }));

The next example takes each item in the array and places them in uppercase inside paragraph HTML tags:

const result = ['red', 'green', 'blue'].map( color => `<p>${color.toUpperCase()}</p>` );
document.write(result);

Notice in this and the previous example, the anonymous function take a parameter, color, which refers to the item in the array. This callback can also take two more parameters–the second parameter refers to the index number in the array and the third refers to the array itself. It’s quite common for callbacks to only used the first, index, parameter, but the next example shows all three parameters being used:

console.log(['red', 'green', 'blue'].map( (color, index, array) => `Element ${index} is ${color}. There are ${array.length} items in total.` ));
//> "Element 0 is red. There are 3 items in total.", "Element 1 is green. There are 3 items in total.", "Element 2 is blue. There are 3 items in total."

Lab 12. Give an array with numerical values, for example [1,2,3,4]. Write a chunk of code to write browser a list as following:

1. Item 1
2. Item 2
3. Item 3
4. Item 4

[Sample]

const so = [1,2,3,4];

document.write("<ol>");
so.map( (x) => document.write(`<li> Mục ${x} </li>`) );
document.write("</ol>");

Lab 13. Given an array with lower characters (for example [le, van, teo]),  Write a chunk of code convert lower characters into upper characters (for example [LE, VAN, TEO]).

[Sample]

const name = ['le','van','teo'];
const result = name.map( (char) => char.toUpperCase());

console.log(result);

– reduce() (p155)

The reduce() method is another method that iterates over each value in the array, but this time it cumulatively combines each result to return just a single value. The callback function is used to describe how to combine each value of the array with the running total. This is often used  to calculate statistics such as averages from data stored in an array. It usually takes two parameters. The first parameter represents the accumulated value of all the calculations so far, and the second parameter represents the current value in the array. The following example shows how to sum an array of numbers:

console.log([1,2,3,4,5].reduce( (acc,val) => acc + val ));
//> 15

The reduce() method also takes a second parameter after the callback, which is the initial value of the accumulator, acc. For example, we could total the numbers in an array, but starting at 10, insteal of zero:

console.log([1,2,3,4,5].reduce( (acc,val) => acc + val, 10 ));
//> 25

Lab 14. Calculating the average word length in a sentence that inputted by user (using prompt to input sentence).

Another example could be to calculate the average word length in a sentence:

const sentence = 'The quick brown for jumped over the lazy dog';

The sentence can be converted into an array using split() method:

const words = sentence.split(' '); // ["The", "quick", "brown", "for", "jumped", "over", "the", "lazy", "dog"]

Now we can use the reduce() function to calculate the total number of letters in the sentence, by starting the count at 0 and adding on the length of each word in each step:

const totalChars = words.reduce( (total, word) => total + word.length,0 );
//>36

And a simple division sum tells us the average word length:

const average = totalChars/words.length;

– filter()

The filter() method returns a new array that only contains items from the original array that return true when passed to the callback.

For example, we can filter an array of numbers to just the even numbers using the following code:

const numbers = [2, 7, 6, 5, 11, 23, 12];
const evens = numbers.filter( x => x % 2 === 0 );
console.log(evens);
// [2, 6, 12]

The filter() method provides a useful way to finding all the truthy values from an array:

const array = [0, 1, '0', false, true, 'hello'];
const result = array.filter(Boolean);
console.log(result);
//> [1, "0", true, "hello"]

To find all the falsy values, the following filter can be used:

const array = [0, 1, '0', false, true, 'hello'];
const result = array.filter( x => !x);
console.log(result);

This uses the not operator, ! to return the complement of a value’s boolean representation. This means that any falsy values will return true and be returned by the filter.

Chaining iterators together (p158)

For example, we can calculate the sum of square numbers using the map() method to square each number in the array and then chain the reduce() method on the end to add the results together:
const result = [1,2,3].map( x => x * x ).reduce( (acc, x) => acc + x );
console.log(result);
//> 14

Improving the mean() function (p159)

Lab 15. Improving the mean() function using a callback. Then:

– Applying to double all the numbers before calculating the mean.

– Applying to square all the numbers before calculating the mean.


Lab 16. Quiz Ninja Project (p161)
-----
Cập nhật: 28/10/2019
-----

Làm web (js03) - JS: Arrays, Logic and Loops

Bài trước: Làm web (js02) - JS: Programming Basics
----------


3         Arrays, Logic, and Loops


In this chapter, we’ll look at some of the data structures used in JavaScript to store lists of values. These are called arrays, sets, and maps. We’ll also look at logical statements that allow us to control the flow of a program, as well as loops that allow us to repeat blocks of code over and over again.

This chapter will cover the following topics:

– Array literals

– Adding and removing values from arrays

– Array methods

– Sets

– Maps

– if and else statements

– switch statements

– while loops

– do … while loops

– for loops

– Iterating over a collection

– Project ― we’ll use arrays, loops and logic to ask multiple questions in our quiz


3.1       Arrays (p89)


3.2       Sets (p103)


Lab 5. Using the prompt to input fullname. Then output characters that used to make the fullname. For example, input: nguyen teo; output: n, g, u, y, e, t, o.

Lab 6. Remove duplicated items in array. For example, inputArray = [1, 2, 4, 5, 1, 3, 5, 6, 7, 3, 5, 4, 7], outputArray = [1, 2, 4, 5, 3, 6, 7]


3.3       Convert Sets to Arrays (p108)


3.4       Maps (p111)


3.5       Convert Maps to Arrays (p115)


3.6       Logic (p115)


3.7       Loops (p119)


3.8       Labs:


Lab 7. Quiz Ninja Project (p128)


-----
Cập nhật: 23/10/2019
-----

Ngu ngơ học làm web (j2) - JS - Biến, alert, confirm, prompt

Tiếp theo của: Ngu ngơ học làm web (j1) - JS - Chương trình đầu tiên, cách debug Javascript
-----

Phần j2. JS – Biến, alert, confirm, prompt


Bài 2: Biến và khai báo biến

- Dùng từ khóa var để khai báo biến

- Biến không được định kiểu trước, mà tùy vào giá trị gán cho nó là gì, thì nó sẽ có kiểu tương ứng.

- Để xuất biến hay chuỗi ra màn hình trình duyệt, dùng hàm document.write(value).

Bài 3: alert, prompt, confirm

- alert(value): để xuất một nội dung ra màn hình, dạng một cửa sổ (popup)

- confirm(value): giống alert(), tuy nhiên có thêm lựa chọn Yes, No. Người dùng bấm Yes hàm này sẽ trả về TRUE, bấm No trả về FALSE.

Ví dụ,

[vidu.js]

            var bt = document.getElementById('click-me');
            bt.addEventListener('click', function() {
                        var content = document.getElementById('text').value;
                        if (confirm(content)) {
                                    alert('Đồng ý');
                        } else {
                                    alert('Không đồng ý');
                        }
            });

- prompt(param1, param2): dùng để lấy thông tin người dùng nhập vào, param1: nội dung thông báo, param2, giá trị khởi tạo. Nếu người dùng nhập nội dung và bấm OK, hàm sẽ trả về nội dung mà người dùng vừa nhập, nếu bấm Cancel, hàm sẽ trả về NULL.

Ví dụ,

[vidu.js]

            var bt = document.getElementById('click-me');
            bt.addEventListener('click', function() {
                        var input = document.getElementById('text');
                        var noiDung = prompt('Nhập vào nội dung:','');
                        input.value = noiDung;
            });

Ví dụ,

Viết đoạn mã Javascript để nhập: Họ, Tên Lót, Tên, Năm Sinh, Email, Giới Tính. Xuất ra màn hình các thông tin vừa nhập theo định dạng:

Họ và Tên:

Tuổi:

Email:

Giới Tính:

[js.html]

<!DOCTYPE html>
<html lang="en">
<head>
            <meta charset="UTF-8">
            <title>Document</title>
</head>
<body>
            <script>
                        var ho, tenLot, ten, namSinh, email, gioiTinh, tuoi, ketQua;

                        ho = prompt('Họ:','');
                        tenLot = prompt('Tên lót:','');
                        ten = prompt('Tên:','');
                        namSinh = prompt('Năm sinh:','');
                        email = prompt('Email:','');
                        gioiTinh = prompt('Giới tính:','');

                        tuoi = new Date().getFullYear() - namSinh;

                        ketQua = 'Họ và Tên: ' + ho + ' '+ tenLot + ' ' + ten;
                        ketQua += '<br>' + 'Tuổi: ' + tuoi;
                        ketQua += '<br>' + 'Email: ' + email;
                        ketQua += '<br>' + 'Giới tính: ' + gioiTinh;

                        document.write(ketQua);

            </script>
</body>
</html>


Lưu ý: dấu + được sử dụng để nối chuỗi. Để lấy năm hiện tại, sử dụng đoạn mã: new Date().getFullYear()
-----------
Cập nhật 18/5/2017
-----------
Xem thêm:
Tổng hợp các bài viết về Ngu ngơ học làm web
Ngu ngơ học làm web (j3) - JS - Toán tử, lệnh If  

Ngu ngơ học làm web (j1) - JS - Chương trình đầu tiên, cách debug Javascript

Tiếp theo của: Ngu ngơ học làm web (j) -
-----

Phần j1. JS – Chương trình đầu tiên, cách debug Javascript


Sẵn dịp học Ajax, học lại luôn kiến thức nền tảng về Javascript, học bài bản một tí để khi đi làm đỡ phải mất thời gian đọc lại.

Đọc và làm theo hướng dẫn của tác giả Thehalfheart (freetuts.net).


Bài 1: Javascript là gì? Viết ứng dụng Javascript đầu tiên


Để ý làm các bài tập ở cuối mỗi bài viết.

Ghi lại một số ý:

- Trình duyệt web sẽ biên dịch và thực thi mã của Javascript

- Mã của Javascript được trình duyệt nhận ra bởi thẻ <script></script>

- Mã của Javascript sẽ nằm lẫn lộn với mã HTML và CSS, khi xử lý tập tin .html (trong tập tin này sẽ có HTML, CSS và Javascript), trình duyệt sẽ xử lý mã theo thứ tự từ trên xuống dưới, từ trái qua phải, gặp cái gì xử lý cái đó. Với các hàm Javascript thì sẽ được biên dịch rồi để đó, chờ có lệnh gọi hàm thì các đoạn mã ở trong hàm sẽ được thực thi.

- Có ba chỗ để đặt mã Javascript khi làm web: internal (đặt trong trang .html, bất kì chỗ nào), external (đặt ngoài trang .html, trong tập tin có đuôi .js, sau đó gọi tập tin này ở trong trang .html), inline (đặt trong thẻ HTML).

Ví dụ một chương trình Javascript:

<!DOCTYPE html>
<html lang="en">
<head>
            <meta charset="UTF-8">
            <title>Document</title>
</head>
<body>
            Nhập nội dung: <input type="text" id="text"><br>
            <button id="click-me">Xuất thông báo</button>

            <script>
                        var bt = document.getElementById('click-me');
                        bt.addEventListener('click', function() {
                        var content = document.getElementById('text').value;
                                    alert(content);
                        });
            </script>

</body>
</html>

Học thêm về cách debug Javascript tại đây:


Xem từ phút thứ 16:45 đến hết.

Ghi lại một số ý liên quan đến debug:

- Mở trang web cần debug

- Mở cửa sổ Developer tools (hoặc F12)

- Tại cửa sổ Developer tools, chọn tab Console để xem thông báo lỗi liên quan đến Javascript (nếu có)

- Tại cửa sổ Developer tools, chọn tab Sources

- Tại khung cửa sổ bên trái (Sources), tìm và mở tập tin chứa mã Javascript

- Tại khung cửa sổ ở giữa (chứa mã Javascript), bấm vào chỉ số hàng để đánh dấu một hoặc nhiều điểm dừng (breakpoint) để xem quá trình chạy của đoạn mã. Hàng nào được đánh dấu sẽ có màu xanh tại chỉ số dòng, và sẽ xuất hiện ở khung cửa sổ bên phải, mục Breakpoints.

- Refesh trang web và chạy các thao tác trên trang web để kích hoạt các đoạn mã Javascript.

- Sử dụng các nút Resume, Step over, Step into, Step out. Tại mục Watch, bấm vào dấu +, nhập tên biến để quan sát nội dung, các thuộc tính của biến.

- Học thêm các chức năng khác liên quan đến debug Javascript.

Ví dụ, về viết Javascript trong thẻ HTML:

<button id="click-me" onclick="alert('hi')">Xuất thông báo</button>

Ví dụ, về gọi Javascript từ tập tin bên ngoài:

[vidu.js]

var bt = document.getElementById('click-me');
                        bt.addEventListener('click', function() {
                                    var content = document.getElementById('text').value;
                                    alert(content);
                        });

[index.html]

<!DOCTYPE html>
<html lang="en">
<head>
            <meta charset="UTF-8">
            <title>Document</title>
</head>
<body>
            Nhập nội dung: <input type="text" id="text"><br>
            <button id="click-me">Xuất thông báo</button>
            <script src="vidu.js"></script>
</body>

</html>
-----------
Cập nhật 17/5/2017
-----------
Xem thêm:
Tổng hợp các bài viết về Ngu ngơ học làm web

Ngu ngơ học làm web (24) - Căn bản JavaScript (7) - More1

tiếp theo của: Ngu ngơ học làm web (23) -  Căn bản JavaScript (6)_Global_OOP
---------

Phần 24.       Căn bản JavaScript (7)_more1


Clip 0: chuẩn bị


Clip 1: thuật ngữ


Clip 2: nội dung khóa học


Clip 3: biến


Clip 4: kiểu dữ liệu


– Primitive types: number, string. boolean

– Special types: null, undefined

– Reference types: array, object

Clip 5: kiểu dữ liệu Object


Clip 6: kiểu dữ liệu Array


    // khai báo đối tượng
    var sv1 = { ten: 'Tèo' };
    var sv2 = { ten: '' };
    var sv3 = { ten: 'Sửu' };

    // mảng các đối tượng
    var lop = [sv1, sv2, sv3];

    console.log(lop);

Clip 7: các phép toán số học


Để ý về thứ thự ưu tiên của các phép toán: nhóm ưu tiên cao (++, --), nhóm ưu tiên thấp hơn (*, /, %), nhóm ưu tiên thấp nhất (+, -); với các phép toán cùng nhóm thì thứ tự sẽ được thực hiện từ trái sang phải.

Clip 8: phép tính tăng, giảm (++, --)


Ví dụ: x = 3; ++x + x-- + --x - x = ?

Clip 9: các phép gán


Các phép gán: =, +=, -=, *=, /=

Các phép gán được thực hiện từ phải qua trái.

Clip 10: hàm (function)


Khi làm việc với một hàm cần để ý hai việc: định nghĩa hàm và gọi hàm để thực thi nó.

Clip 11: phương thức của đối tượng (object methods)


Là một hình thức của lập trình hướng đối tượng. Thực hiện định nghĩa phương thức ngay trong đối tượng (chứ không định nghĩa phương thức trong lớp).

sinhvien = {
        ten: 'Teo',
        tuoi: 20,
        chao: function(){
            console.log('Teo chao cac ban!');
        }
    };
      // xuất nội dung phương thức
    console.log(sinhvien.chao);
      // thực thi phương thức
    sinhvien.chao();

Clip 12: toán tử so sánh


Một số phép toán so sánh: > >= < <= == === != !==

Clip 13: vòng lặp for


for(lam1; lam2; lam4)
{
lam3;
}

Ví dụ:

for(var i = 1; i <= 10; i++){
        console.log(i);
    }

Clip 14: vòng lặp for…of, for…in


– Vòng lặp for…of

    var lopDaiHocChuTo = [ 
        { STT: 1, ten: 'Teo', tuoi: 10},
        { STT: 2, ten: 'Ti', tuoi: 11},
        { STT: 3, ten: 'Mui', tuoi: 12},
        { STT: 4, ten: 'Suu', tuoi: 13},
    ]
    for(sinhVien of lopDaiHocChuTo{
        console.log(sinhVien.ten + ' ' + sinhVien.tuoi);
    }

– Vòng lặp for…in

    var sinhVien = {
        ten: "Tèo",
        tuoi: 20,
        gioiTinh: 1
    }
    for(var key in sinhVien{
        console.log(key + ':' + sinhVien[key]);
    }

Clip 15: array methods


Đọc các array methods ở đây: https://developer.mozilla.org/en-


– a.concat(b): nối mảng a với mảng b

– a.push(x): thêm giá trị x vào cuối mảng a, trả về số phần tử của mảng sau khi thêm

– a.pop(): lấy phần tử cuối ra khỏi mảng, trả về giá trị lấy được

– a.shift(): lấy phần tử đầu ra khỏi mảng, trả về giá trị lấy được

– a.unshift(x): thêm một/hoặc nhiều phần tử vào đầu mảng

Clip 16: dùng hàm như một tham số (callback):


Sử dụng hàm callback: là hàm (A) gọi hàm (B) thông qua việc truyền tham số (B là tham số của hàm A); và hàm này (B) chỉ được thực hiện khi hàm kia (A) thực hiện. Hàm B được gọi là hàm callback.

Khai báo một đối tượng:

var coffeeMachine = {
    makeCoffee: function() {
        console.log('making coffee...');
    }
};
// chạy hàm makeCoffee
coffeeMachine.makeCoffee();

Truyền một hàm cho một hàm khác:

var coffeeMachine = {
    makeCoffee: function(onFinish) {
        console.log('making coffee...');
        onFinish();
    }
};
var beep = function(){
    console.log('bip bip...');
}
// chạy hàm makeCoffee
coffeeMachine.makeCoffee(beep);

Có thể định nghĩa hàm (hàm B) như một tham số (của hàm A) khi thực thi:

var coffeeMachine = {
    makeCoffee: function(onFinish) {
        console.log('making coffee...');
        onFinish();
    }
};
// định nghĩa hàm callback khi thực thi
coffeeMachine.makeCoffee(function(){
    console.log("ting ting...");
});

Clip 17: array.map()


Map nghĩa là ánh xạ, kiểu như một hàm số y = f(x) = 2x chẳng hạn. Với x = 1, thì y = 2; x = 2 thì y = 4 ; x = 3 thì y = 6…v.v.

Map sẽ tạo ra mảng mới bằng cách thay đổi giá trị của từng phần tử trong mảng cũ.

Cú pháp :

let newArray = oldArray.map(function(moiGiaTriCuaMangCu){
    // biến đổi mỗi giá trị của mảng cũ
    return giá_trị_đã_được_biến_đổi
});


 Ví dụ :

let numbers = [1, 4, 9]
let doubles = numbers.map(function(num) {
  return num * 2
})
// doubles is now   [2, 8, 18]
// numbers is still [1, 4, 9]

console.log(doubles);
-----------
Cập nhật [3/9/2020]
-----------