[Thực hành] Mảng- Codegym.vn

Apr 21, 2020 | Bài thực hành, Blog | 0 comments

Mục tiêu

Thực hành kiến thức về mảng

Mô tả- mảng

Hướng dẫn- mảng

Bước 1:  Truy cập vào https://github.com/codegym-vn/typescript-demo , đọc README, clone dự án.

Bước 2:  Thực thi lệnh npm i tại thư mục dự án vừa clone về, để cài đặt các packages cần thiết.

Bước 3:  Mở dự án mẫu với editor mà các bạn quen thuộc

mảng

Bước 4: Chạy lệnh npm start, sau đó trình duyệt sẽ tự động mở trang web localhost:3000, các bạn có thể nhìn thấy danh mục bài học như sau:

mảng

Bước 5: Di chuyển vào link của bài học 3.

Bước 6: Mở file src/array.ts trong project vừa tạo, sau đó code lần lượt các đoạn code sau:

============================================
/**
 * Array
 */

// declare an array

const list: number[] = [1, 2, 3];

const categories: Array<string> =
    ['Sport', 'IT', 'Car'];

console.log('list');
list.forEach((num) =>
    console.log(num.toFixed(2))
);

console.log('categries');
categories.forEach((str) =>
    console.log(str.includes('a'))
);

Expected:
    list
1.00
2.00
3.00
categries
false (2 lần)
true

============================================
// convert mảng từ dạng này sang dạng khác.
const listSquare = list.map(num => num * num);
console.log(listSquare)
// Output: [1, 4, 9]

// lọc các phần tử thỏa mãn
const result = categories.filter(str => str.length > 2)
console.log(result);
// Output: ['Sport', 'Car']

/**
 * Tuple
 */

// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
// x = [10, "hello"]; // Error

console.log(x[0].substr(1)); // OK
// console.log(x[1].substr(1));
// Error, Property 'substr' does not exist on type 'number'.

x[3] = "world";
// OK, 'string' can be assigned to 'string | number'
x[5] = 100.25;
console.log(x[5].toString());
// OK, 'string' and 'number' both have 'toString'

Expected:
    [1, 4, 9]
        ["Sport", "Car"]
ello
100.25
============================================
x[6] = true; // Error, 'boolean' isn't 'string | number'
Expected: TS2322: Type 'true' is not assignable to type 'string | number'.

Mã nguồn tham khảo: https://github.com/codegym-vn/typescript-demo/tree/master/src

Trên đây CodeGym đã cùng với bạn luyện tập về mảng. Hãy chụp ảnh màn hình và nộp bài thực hành của bạn trên CodeGymX để cùng nhau luyện tập nhé!

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

BÀI VIẾT LIÊN QUAN

BẠN MUỐN HỌC LẬP TRÌNH?

GỌI NGAY 

098 953 44 58

Nhận tư vấn, định hướng 1-1

Điền và gửi thông tin cá nhân để được tư vấn miễn phí về các chương trình học.

5 + 13 =