Welcome 🎉

logo

ReactLMS

Search
Light Mode
Contact Us

4 min to read

Contact us

No results for your search.
Sorry, an unexpected error occurred

Concept


Arrays are an important part of JavaScript programming, allowing you to store and manage multiple values in a single data structure.


Declare and initialize an array


In JavaScript, we can declare and initialize an array using square brackets [].

let numbers = [1, 2, 3, 4, 5];
let fruits = ["apple", "banana", "orange"];






In the example above, we created an array called numbers with 5 elements ranging from 1 to 5, and an array called fruits with 3 elements representing different types of fruits.


Accessing and editing elements in an array


To access an element in an array, we can use the index of that element. Indexes in JavaScript start from 0.

let numbers = [1, 2, 3, 4, 5];

console.log(numbers[0]); // Kết quả: 1
console.log(numbers[2]); // Kết quả: 3






We can also edit the value of an element in the array by assigning a new value to that element.

let numbers = [1, 2, 3, 4, 5];
numbers[2] = 10;

console.log(numbers); // Kết quả: [1, 2, 10, 4, 5]







Array methods


JavaScript provides many useful methods for manipulating arrays. Here are some popular methods:


Here is an example of how to use some of these methods:

let fruits = ["apple", "banana", "orange"];

fruits.push("grape"); // Thêm "grape" vào cuối mảng
fruits.pop(); // Xóa phần tử cuối cùng khỏi mảng

fruits.shift(); // Xóa phần tử đầu tiên khỏi mảng
fruits.unshift("kiwi"); // Thêm "kiwi" vào đầu mảng

let slicedFruits = fruits.slice(1, 3); // Sao chép các phần tử từ chỉ số 1 đến 2 (không bao gồm chỉ số 3)
fruits.splice(1, 2, "pear", "pineapple"); // Xóa 2 phần tử từ chỉ số 1 và thay thế bằng "pear" và "pineapple"

console.log(fruits); // Kết quả: ["kiwi", "pear", "pineapple"]
console.log(slicedFruits); // Kết quả: ["pear", "pineapple"]







Looping through elements in an array


To iterate through each element in the array, we can use a for loop or a forEach loop.

let numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

numbers.forEach(function(number) {
  console.log(number);
});






Both of these methods will display the elements in the numbers array on the console.




Read more
On This Page