Trong hướng dẫn này, bạn sẽ tìm hiểu về mảng JavaScript với sự trợ giúp của các ví dụ.
Mảng là một đối tượng có thể lưu trữ nhiều phần tử . Ví dụ,
const myArray = ['hello', 'world', 'welcome'];
Tạo một mảng
Bạn có thể tạo một mảng bằng hai cách:
1. Sử dụng một ký tự mảng
Cách dễ nhất để tạo một mảng là sử dụng một ký tự mảng []
. Ví dụ,
const array1 = ["eat", "sleep"];
2. Sử dụng từ khóa mới
Bạn cũng có thể tạo một mảng bằng cách sử dụng new
từ khóa của JavaScript .
const array2 = new Array("eat", "sleep");
Trong cả hai ví dụ trên, chúng ta đã tạo một mảng có hai phần tử.
Lưu ý : Nên sử dụng ký tự mảng để tạo mảng.
Dưới đây là các ví dụ khác về mảng:
// empty array
const myList = [ ];
// array of numbers
const numberArray = [ 2, 4, 6, 8];
// array of strings
const stringArray = [ 'eat', 'work', 'sleep'];
// array with mixed data types
const newData = ['work', 'exercise', 1, true];
Bạn cũng có thể lưu trữ mảng, hàm và các đối tượng khác bên trong một mảng. Ví dụ,
const newData = [
{'task1': 'exercise'},
[1, 2 ,3],
function hello() { console.log('hello')}
];
Truy cập các phần tử của một mảng
Bạn có thể truy cập các phần tử của mảng bằng các chỉ số (0, 1, 2…) . Ví dụ,
const myArray = ['h', 'e', 'l', 'l', 'o'];
// first element
console.log(myArray[0]); // "h"
// second element
console.log(myArray[1]); // "e"
Lập chỉ mục mảng trong JavaScript
Lưu ý : Chỉ mục của Array bắt đầu bằng 0, không phải 1.
Thêm một phần tử vào một mảng
Bạn có thể sử dụng phương thức tích hợp sẵn push()
và unshift()
thêm các phần tử vào một mảng.
Các push()
phương pháp bổ sung thêm một yếu tố ở phần cuối của mảng. Ví dụ,
let dailyActivities = ['eat', 'sleep'];
// add an element at the end
dailyActivities.push('exercise');
console.log(dailyActivities); // ['eat', 'sleep', 'exercise']
Các unshift()
phương pháp bổ sung thêm một yếu tố ở phần đầu của mảng. Ví dụ,
let dailyActivities = ['eat', 'sleep'];
//add an element at the start
dailyActivities.unshift('work');
console.log(dailyActivities); // ['work', 'eat', 'sleep']
Thay đổi các phần tử của một mảng
Bạn cũng có thể thêm các phần tử hoặc thay đổi các phần tử bằng cách truy cập vào giá trị chỉ mục.
let dailyActivities = [ 'eat', 'sleep'];
// this will add the new element 'exercise' at the 2 index
dailyActivities[2] = 'exercise';
console.log(dailyActivities); // ['eat', 'sleep', 'exercise']
Giả sử, một mảng có hai phần tử. Nếu bạn cố gắng thêm một phần tử ở chỉ mục 3 (phần tử thứ tư), phần tử thứ ba sẽ không được xác định. Ví dụ,
let dailyActivities = [ 'eat', 'sleep'];
// this will add the new element 'exercise' at the 3 index
dailyActivities[3] = 'exercise';
console.log(dailyActivities); // ["eat", "sleep", undefined, "exercise"]
Về cơ bản, nếu bạn cố gắng thêm các phần tử vào các chỉ số cao, các chỉ số ở giữa sẽ có giá trị không xác định.
Xóa một phần tử khỏi một mảng
Bạn có thể sử dụng pop()
phương thức để xóa phần tử cuối cùng khỏi một mảng. Các pop()
phương pháp cũng trả về giá trị trả lại. Ví dụ,
let dailyActivities = ['work', 'eat', 'sleep', 'exercise'];
// remove the last element
dailyActivities.pop();
console.log(dailyActivities); // ['work', 'eat', 'sleep']
// remove the last element from ['work', 'eat', 'sleep']
const removedElement = dailyActivities.pop();
//get removed element
console.log(removedElement); // 'sleep'
console.log(dailyActivities); // ['work', 'eat']
Nếu bạn cần loại bỏ phần tử đầu tiên, bạn có thể sử dụng shift()
phương pháp. Các shift()
phương pháp loại bỏ các yếu tố đầu tiên và cũng có thể trả về phần tử loại bỏ. Ví dụ,
let dailyActivities = ['work', 'eat', 'sleep'];
// remove the first element
dailyActivities.shift();
console.log(dailyActivities); // ['eat', 'sleep']
Độ dài mảng
Bạn có thể tìm độ dài của một phần tử (số phần tử trong một mảng) bằng cách sử dụng thuộc length
tính. Ví dụ,
const dailyActivities = [ 'eat', 'sleep'];
// this gives the total number of elements in an array
console.log(dailyActivities.length); // 2
Phương thức mảng
Trong JavaScript, có sẵn nhiều phương thức mảng khác nhau giúp thực hiện các phép tính hữu ích dễ dàng hơn.
Một số phương pháp mảng JavaScript thường được sử dụng là:
Method | Decfscription |
---|---|
concat() | joins two or more arrays and returns a result |
indexOf() | searches an element of an array and returns its position |
find() | returns the first value of an array element that passes a test |
findIndex() | returns the first index of an array element that passes a test |
forEach() | calls a function for each element |
includes() | checks if an array contains a specified element |
push() | aads a new element to the end of an array and returns the new length of an array |
unshift() | adds a new element to the beginning of an array and returns the new length of an array |
pop() | removes the last element of an array and returns the removed element |
shift() | removes the first element of an array and returns the removed element |
sort() | sorts the elements alphabetically in strings and in ascending order |
slice() | selects the part of an array and returns the new array |
splice() | removes or replaces existing elements and/or adds new elements |
Ví dụ: Phương thức mảng JavaScript
let dailyActivities = ['sleep', 'work', 'exercise']
let newRoutine = ['eat'];
// sorting elements in the alphabetical order
dailyActivities.sort();
console.log(dailyActivities); // ['exercise', 'sleep', 'work']
//finding the index position of string
const position = dailyActivities.indexOf('work');
console.log(position); // 2
// slicing the array elements
const newDailyActivities = dailyActivities.slice(1);
console.log(newDailyActivities); // [ 'sleep', 'work']
// concatenating two arrays
const routine = dailyActivities.concat(newRoutine);
console.log(routine); // ["exercise", "sleep", "work", "eat"]
Lưu ý : Nếu phần tử không nằm trong mảng, indexOf()
cho -1.
Truy cập Phương thức mảng JavaScript để tìm hiểu thêm.
Hoạt động của Mảng JavaScript
Trong JavaScript, một mảng là một đối tượng. Và, các chỉ số của mảng là các khóa đối tượng.
Vì mảng là các đối tượng nên các phần tử của mảng được lưu trữ bằng tham chiếu. Do đó, khi một giá trị mảng được sao chép, bất kỳ thay đổi nào trong mảng được sao chép cũng sẽ phản ánh trong mảng ban đầu. Ví dụ,
let arr = ['h', 'e'];
let arr1 = arr;
arr1.push('l');
console.log(arr); // ["h", "e", "l"]
console.log(arr1); // ["h", "e", "l"]
Bạn cũng có thể lưu trữ các giá trị bằng cách chuyển một khóa được đặt tên trong một mảng. Ví dụ,
let arr = ['h', 'e'];
arr.name = 'John';
console.log(arr); // ["h", "e"]
console.log(arr.name); // "John"
console.log(arr['name']); // "John"
Lập chỉ mục mảng trong JavaScript
Tuy nhiên, không nên lưu trữ các giá trị bằng cách chuyển các tên tùy ý vào một mảng.
Do đó trong JavaScript, bạn nên sử dụng một mảng nếu các giá trị nằm trong bộ sưu tập có thứ tự. Nếu không, tốt hơn là sử dụng đối tượng với { }
.