Array(陣列)

在 JavaScript 中,陣列(Array)是一種用來存儲多個值的資料結構。陣列中的值可以是任意類型,包括數字、字串、物件、甚至其他陣列。陣列提供了許多方法來處理和操作其內部的元素。

創建陣列

  1. 使用字面量語法

    const fruits = ["apple", "banana", "cherry"];
    
    
  2. 使用 Array 構造函數

    const numbers = new Array(1, 2, 3, 4);
    const emptyArray = new Array(5); // 創建一個長度為 5 的空陣列
    
    

陣列的基本操作

  1. 存取元素

    使用索引(從 0 開始)來存取或修改陣列中的元素。

    const fruits = ["apple", "banana", "cherry"];
    console.log(fruits[1]); // "banana"
    fruits[1] = "blueberry";
    console.log(fruits[1]); // "blueberry"
    
    
  2. 陣列長度

    使用 length 屬性來獲取或設定陣列的長度。

    const fruits = ["apple", "banana", "cherry"];
    console.log(fruits.length); // 3
    fruits.length = 2;
    console.log(fruits); // ["apple", "banana"]
    
    
  3. 常用方法

陣列的其他特性

陣列在 JavaScript 中是非常靈活且強大的資料結構,支持多種方法和操作來處理資料。了解和掌握這些基本操作對於進行有效的程式設計至關重要。

傳值呼叫Call by Value和傳址呼叫Call by Reference

在程式設計中,「傳值呼叫」(Call by Value)和「傳址呼叫」(Call by Reference)是兩種將參數傳遞給函數的方法。這兩種方法會影響函數如何處理傳遞給它的參數。以下是對這兩種方法的詳細介紹:

傳值呼叫(Call by Value)