Create Array
การสร้าง Array สามารถทำได้หลายวิธี โดยใช้ลิตาเรอ (Literal) หรือคอนสตรัคเตอร์
js
// Using array literal
const arr1 = [1, 2, 3, 4, 5];
// Using Array constructor
const arr2 = new Array(5); // Creates an array with 5 empty slots
const arr3 = new Array(1, 2, 3, 4, 5); // Creates an array with the given elements
Access Array
การเข้าถึงสมาชิกของ Array สามารถทำได้โดยใช้ดัชนี (Index) ซึ่งเริ่มจาก 0 และใช้ลูปเพื่อเข้าถึงสมาชิกทั้งหมด
js
const arr = [10, 20, 30, 40, 50];
// Accessing elements by index
const firstElement = arr[0]; // 10
const secondElement = arr[1]; // 20
// Using loop to access all elements
arr.forEach((element, index) => {
console.log(`Element at index ${index} is ${element}`);
});
Modify Array
การจัดการและเปลี่ยนแปลงสมาชิกของ Array สามารถทำได้ด้วยเมธอดต่างๆ เช่น การเพิ่ม, ลบ, หรือการค้นหา
js
let arr = [1, 2, 3];
// Adding elements
arr.push(4); // [1, 2, 3, 4]
arr.unshift(0); // [0, 1, 2, 3, 4]
// Removing elements
arr.pop(); // [0, 1, 2, 3]
arr.shift(); // [1, 2, 3]
// Finding elements
const index = arr.indexOf(2); // 1
const found = arr.find(element => element > 2); // 3
Array Methods
เมธอดต่างๆ สำหรับการจัดการ Array เช่น การรวม, การแบ่ง, การกรอง, และการแปลง
js
const arr = [1, 2, 3, 4, 5];
// Combining arrays
const arr2 = [6, 7, 8];
const combined = arr.concat(arr2); // [1, 2, 3, 4, 5, 6, 7, 8]
// Slicing arrays
const sliced = arr.slice(1, 4); // [2, 3, 4]
// Mapping and filtering
const doubled = arr.map(x => x * 2); // [2, 4, 6, 8, 10]
const even = arr.filter(x => x % 2 === 0); // [2, 4]
// Reducing
const sum = arr.reduce((acc, curr) => acc + curr, 0); // 15
ES6+ Features
คุณสมบัติใหม่ที่เพิ่มเข้ามาใน ES6+ ที่เกี่ยวข้องกับ Array เช่น Spread operator, Destructuring, และ Array methods ใหม่
js
const arr = [1, 2, 3, 4, 5];
// Spread operator
const newArr = [...arr, 6, 7]; // [1, 2, 3, 4, 5, 6, 7]
// Destructuring
const [first, second, ...rest] = arr; // first = 1, second = 2, rest = [3, 4, 5]
// Array.from
const str = 'hello';
const charArray = Array.from(str); // ['h', 'e', 'l', 'l', 'o']
Array with Objects
การทำงานร่วมกับ Array และ Object เช่น การแปลง Object เป็น Array หรือการสร้าง Array จาก Object
js
const obj = {
a: 1,
b: 2,
c: 3
};
// Converting object to array
const entries = Object.entries(obj); // [['a', 1], ['b', 2], ['c', 3]]
const keys = Object.keys(obj); // ['a', 'b', 'c']
const values = Object.values(obj); // [1, 2, 3]