在 JavaScript 中,數組 是一種特殊類型的對象,用於儲存有序的資料集合。陣列可以保存不同資料類型的多個值,包括數字、字串、對象,甚至其他陣列。
建立陣列最常見的方法是使用方括號 []。
範例:
const fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]
此方法建立一個空數組或具有指定元素的陣列。
範例:
const numbers = new Array(5); // Creates an array with 5 empty slots console.log(numbers.length); // Output: 5 const colors = new Array("Red", "Green", "Blue"); console.log(colors); // Output: ["Red", "Green", "Blue"]
使用從零開始的索引存取陣列元素。
範例:
const fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]
const numbers = new Array(5); // Creates an array with 5 empty slots console.log(numbers.length); // Output: 5 const colors = new Array("Red", "Green", "Blue"); console.log(colors); // Output: ["Red", "Green", "Blue"]
const fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits[0]); // Output: Apple console.log(fruits[2]); // Output: Cherry
fruits[1] = "Blueberry"; console.log(fruits); // Output: ["Apple", "Blueberry", "Cherry"]
fruits.push("Mango"); console.log(fruits); // Output: ["Apple", "Banana", "Cherry", "Mango"]
fruits.pop(); console.log(fruits); // Output: ["Apple", "Banana"]
fruits.unshift("Strawberry"); console.log(fruits); // Output: ["Strawberry", "Apple", "Banana"]
fruits.shift(); console.log(fruits); // Output: ["Apple", "Banana"]
console.log(fruits.indexOf("Banana")); // Output: 1
console.log(fruits.includes("Cherry")); // Output: false
const numbers = [1, 2, 3]; const squared = numbers.map((num) => num ** 2); console.log(squared); // Output: [1, 4, 9]
const evenNumbers = numbers.filter((num) => num % 2 === 0); console.log(evenNumbers); // Output: [2]
const sum = numbers.reduce((acc, curr) => acc + curr, 0); console.log(sum); // Output: 6
const moreFruits = ["Peach", "Grape"]; const allFruits = fruits.concat(moreFruits); console.log(allFruits); // Output: ["Apple", "Banana", "Peach", "Grape"]
const sliced = allFruits.slice(1, 3); console.log(sliced); // Output: ["Banana", "Peach"]
allFruits.splice(1, 1, "Orange"); console.log(allFruits); // Output: ["Apple", "Orange", "Peach", "Grape"]
for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); }
陣列可以包含其他數組,建立矩陣或多維結構。
範例:
for (let fruit of fruits) { console.log(fruit); }
fruits.forEach((fruit) => console.log(fruit));
const matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; console.log(matrix[1][2]); // Output: 6
解構可讓您將陣列中的值提取到變數中。
範例:
const fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]
嗨,我是 Abhay Singh Kathayat!
我是一名全端開發人員,擁有前端和後端技術的專業知識。我使用各種程式語言和框架來建立高效、可擴展且用戶友好的應用程式。
請隨時透過我的商務電子郵件與我聯繫:kaashshorts28@gmail.com。
以上是理解 JavaScript 中的數組的詳細內容。更多資訊請關注PHP中文網其他相關文章!