日期:2024 年 12 月 13 日
歡迎來到 JavaScript 之旅的第六天!今天,我們深入研究 JavaScript 中的兩個基本資料結構:陣列 和 物件。這些結構構成了現代 Web 開發中資料操作的支柱。透過掌握陣列和對象,您將解鎖有效儲存、存取和轉換資料的強大方法。
陣列是儲存在連續記憶體位置的項目(稱為元素)的集合。在 JavaScript 中,陣列用途廣泛,可以保存混合資料類型。
// Empty array let emptyArray = []; // Array with initial elements let fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits); // Output: ["Apple", "Banana", "Cherry"] // Mixed data types let mixedArray = [42, "Hello", true]; console.log(mixedArray); // Output: [42, "Hello", true]
範例:
let numbers = [1, 2, 3]; numbers.push(4); // Adds 4 to the end console.log(numbers); // Output: [1, 2, 3, 4] numbers.pop(); // Removes the last element console.log(numbers); // Output: [1, 2, 3] numbers.unshift(0); // Adds 0 to the beginning console.log(numbers); // Output: [0, 1, 2, 3] numbers.shift(); // Removes the first element console.log(numbers); // Output: [1, 2, 3]
let nums = [1, 2, 3, 4]; let squares = nums.map(num => num * num); console.log(squares); // Output: [1, 4, 9, 16]
let ages = [12, 18, 22, 16]; let adults = ages.filter(age => age >= 18); console.log(adults); // Output: [18, 22]
let numbers = [1, 2, 3, 4]; let sum = numbers.reduce((acc, curr) => acc + curr, 0); console.log(sum); // Output: 10
物件是屬性的集合,其中每個屬性都是鍵值對。物件非常適合表示具有屬性的現實世界實體。
let person = { name: "Arjun", age: 22, isStudent: true, }; console.log(person.name); // Output: Arjun console.log(person["age"]); // Output: 22
let car = { brand: "Tesla", }; car.model = "Model 3"; // Adding a new property car.brand = "Ford"; // Updating a property console.log(car); // Output: { brand: "Ford", model: "Model 3" }
delete car.model; console.log(car); // Output: { brand: "Ford" }
範例:
// Empty array let emptyArray = []; // Array with initial elements let fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits); // Output: ["Apple", "Banana", "Cherry"] // Mixed data types let mixedArray = [42, "Hello", true]; console.log(mixedArray); // Output: [42, "Hello", true]
Feature | Arrays | Objects |
---|---|---|
Storage | Ordered collection of items. | Unordered collection of key-value pairs. |
Access | Index-based (arr[0]). | Key-based (obj.key). |
Best Use Case | List of related items. | Grouping attributes of an entity. |
let numbers = [1, 2, 3]; numbers.push(4); // Adds 4 to the end console.log(numbers); // Output: [1, 2, 3, 4] numbers.pop(); // Removes the last element console.log(numbers); // Output: [1, 2, 3] numbers.unshift(0); // Adds 0 to the beginning console.log(numbers); // Output: [0, 1, 2, 3] numbers.shift(); // Removes the first element console.log(numbers); // Output: [1, 2, 3]
let nums = [1, 2, 3, 4]; let squares = nums.map(num => num * num); console.log(squares); // Output: [1, 4, 9, 16]
let ages = [12, 18, 22, 16]; let adults = ages.filter(age => age >= 18); console.log(adults); // Output: [18, 22]
後續步驟
在以上是探索 JavaScript 中的陣列和對象的詳細內容。更多資訊請關注PHP中文網其他相關文章!