JavaScript 中數組和對象是非常重要的概念。它們是瀏覽器中數據存儲的主要方式,幾乎所有的 JavaScript 應用都會使用它們。
數組是一個可以存儲多個值的變量,這些值可以是任何類型。數組的元素由數字索引,從 0 開始,可以通過這個索引訪問和修改數組中的元素。例如:
var myArray = ["apple", "banana", "orange"]; console.log(myArray[0]); //輸出“apple” myArray[1] = "grape"; console.log(myArray); //輸出["apple", "grape", "orange"]
對象是一個無序的集合,其中包括各種屬性和方法。屬性是一種以“key-value”方式存儲的變量。這個“key”是字符串類型,用于訪問這個屬性的值。例如:
var myObject = { name: "Tom", age: 20, sayHello: function() { console.log("Hello, my name is " + this.name); } }; console.log(myObject.name); //輸出“Tom” myObject.sayHello(); //輸出“Hello, my name is Tom”
對象中的屬性可以隨時增加、刪除和修改。例如:
myObject.school = "ABC"; console.log(myObject); //輸出{name: "Tom", age: 20, sayHello: ?, school: "ABC"} delete myObject.age; console.log(myObject); //輸出{name: "Tom", sayHello: ?, school: "ABC"} myObject.sayHello = function() { console.log("Hi, " + this.name + " is saying hello!"); }; myObject.sayHello(); //輸出“Hi, Tom is saying hello!”
數組和對象可以組合在一起,叫做數組對象。例如:
var myArrayObject = [ {name: "Tom", age: 20}, {name: "Jerry", age: 18}, {name: "Bob", age: 25} ]; console.log(myArrayObject[1].name); //輸出“Jerry” myArrayObject[2].age = 28; console.log(myArrayObject); //輸出[{name: "Tom", age: 20}, {name: "Jerry", age: 18}, {name: "Bob", age: 28}]
數組對象可以非常靈活地存儲多個數據。例如,一個網站的用戶列表可以用數組對象表示:
var userList = [ {name: "Tom", age: 20, gender: "male", email: "tom@example.com"}, {name: "Jerry", age: 18, gender: "male", email: "jerry@example.com"}, {name: "Jessica", age: 25, gender: "female", email: "jessica@example.com"} ];
數組對象還可以通過循環語句進行遍歷。例如,下面是一個用 for 循環輸出數組對象屬性的代碼:
for (var i = 0; i< userList.length; i++) { console.log(userList[i].name + " is a " + userList[i].age + "-year-old " + userList[i].gender + ", email is " + userList[i].email); } //輸出“Tom is a 20-year-old male, email is tom@example.com” //輸出“Jerry is a 18-year-old male, email is jerry@example.com” //輸出“Jessica is a 25-year-old female, email is jessica@example.com”
總之,JavaScript 中的數組和對象是非常強大的數據類型,它們可以幫助我們組織和存儲各種復雜的數據。熟悉數組和對象的使用方式,對于成為一名合格的 JavaScript 開發者來說是非常重要的。