許多高級語言都支援物件導向,例如 C++、C#、Java。一般來說,物件導向語言需要具備以下能力:
JavaScript 雖然不是傳統意義上的類別語言,但它透過物件、原型與函式,也能實現類似的效果。
Object 是 JavaScript 中非常核心的型別,它可以包含屬性與方法。建立物件常見的方式有以下幾種。
var box = new Object();
box.name = "張三";
box.age = 23;
box.run = function() {
return "我是中國人!";
};
document.write(typeof box + "<br/>");
document.write(box.name + "<br/>");
document.write(box.age + "<br/>");
document.write(box.run());
var box = {
name: "張三",
age: 23,
run: function() {
return "我是中國人!";
}
};
document.write(box.name);
document.write(box.age);
document.write(box.run());
當函式需要多個參數時,可以將參數封裝在物件中,讓呼叫更靈活。
function box(obj) {
if (obj.name !== undefined) document.write(obj.name + "<br/>");
if (obj.age !== undefined) document.write(obj.age + "<br/>");
}
box({ name: "張三", age: 23 });
JavaScript 的陣列可以存放任意型別的元素,而且長度可以動態調整。
var box = new Array(1, 2, 3, 4); document.write(box); // 1,2,3,4 var box2 = [1, 2, 3, 4]; document.write(box2.length); // 4

陣列具有 toString()、valueOf()、toLocaleString() 等方法,預設會以逗號分隔元素。
var box = [1, 2, 3, 4]; document.write(box.toString()); document.write(box.valueOf()); document.write(box.toLocaleString());
若要自訂分隔符號,可以使用 join():
var box = [1, 2, 3, 4];
document.write(box.join("-"));

堆疊是後進先出的資料結構。JavaScript 陣列提供 push() 與 pop() 來模擬堆疊行為。
var box = [1, 2, 3, 4]; box.push(5, 6); box.pop();


佇列是先進先出的資料結構。可以用 push() 從尾端加入元素,再用 shift() 從前端移除元素。
var box = [1, 2, 3, 4]; box.push(5, 6); box.shift();

另外,unshift() 可以在陣列前端加入元素。
var box = [1, 2, 3, 4]; box.unshift(0);

reverse() 可以反轉陣列順序,sort() 則可以排序。
var box = [1, 2, 3, 4, 5]; box.reverse(); var box2 = [3, 2, 6, 4, 1, 5]; box2.sort();
但 sort() 預設是依字串順序排序,若要依數字大小排序,需要自訂比較函式:
function compare(value1, value2) {
if (value1 < value2) return -1;
if (value1 > value2) return 1;
return 0;
}
var box = [0, 15, 10, 1, 5];
box.sort(compare);
concat() 可以合併陣列並回傳新陣列:
var box = [1, 2, 3, 4, 5]; var box1 = box.concat(6);
slice() 可以擷取部分元素:
var box = [1, 2, 3, 4, 5]; var box1 = box.slice(2, 4);
splice() 則可以刪除、插入或替換元素:
var box = [1, 2, 3, 4, 5]; var removed = box.splice(0, 2); // 刪除 box.splice(4, 0, 6); // 插入 box.splice(4, 1, 6); // 替換
物件與陣列是 JavaScript 最基礎也最重要的資料結構。掌握它們的建立方式、轉換方法、堆疊與佇列操作、排序與修改技巧,能大幅提升我們處理資料的能力。