對象聲明三大模式
1. 字面量 / 對象初始化器 (最常用)
var user = {
id: 1001,
name: '張三',
age: 25,
skills: ['JS', 'Vue', 'Node'],
greet: function() {
console.log('Hi, ' + this.name);
},
// ES6 簡寫
getName() { return this.name; },
// 計算屬性名
['skill_' + 0]: 'JavaScript'
};
user.greet(); // Hi, 張三
user['skill_0']; // JavaScript
2. 構造函數 + 原型 (傳統類模擬)
function Person(name, age) {
// 實例屬性
this.name = name;
this.age = age;
// 實例方法 (不推薦,每實例創建新函數)
// this.sayHi = function() {...}
}
// 原型方法 (共享)
Person.prototype.sayHi = function() {
console.log('我是 ' + this.name);
};
Person.prototype.species = 'Human'; // 共享屬性
var p1 = new Person('李四', 30);
var p2 = new Person('王五', 28);
p1.sayHi(); // 我是 李四
console.log(p1.species); // Human
// 動態擴展原型影響所有實例
Person.prototype.getBirthYear = function() {
return new Date().getFullYear() - this.age;
};
console.log(p1.getBirthYear()); // 可用
3. ES6 Class (語法糖,底層仍是原型)
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
// 原型方法
sayHi() { console.log(`我是 ${this.name}`); }
// 靜態方法
static createBaby(name) { return new Person(name, 0); }
// Getter/Setter
get birthYear() { return new Date().getFullYear() - this.age; }
set birthYear(year) { this.age = new Date().getFullYear() - year; }
}
class Student extends Person {
constructor(name, age, grade) {
super(name, age); // 必須先調用 super()
this.grade = grade;
}
sayHi() {
super.sayHi(); // 調用父類方法
console.log(`讀 ${this.grade} 年級`);
}
}
const s = new Student('趙六', 12, 6);
s.sayHi(); // 我是 趙六 / 讀 6 年級
對象屬性特性控制 (ES5 Object.defineProperty)
var obj = {};
Object.defineProperty(obj, 'readonly', {
value: '不可變',
writable: false, // 嚴格模式下拋錯
configurable: false, // 不可刪除/重新定義
enumerable: true // for...in 可見
});
Object.defineProperty(obj, 'secret', {
get: function() { return this._secret; },
set: function(val) { this._secret = val.toUpperCase(); },
enumerable: true,
configurable: true
});
obj.secret = 'hello';
console.log(obj.secret); // HELLO
數組聲明與核心操作
聲明方式
// 1. 字面量 (推薦)
var arr1 = [1, 2, 3];
var arr2 = []; arr2[0] = 10;
// 2. 構造函數
var arr3 = new Array(3); // [empty × 3] 稀疏數組
var arr4 = new Array(1,2,3); // [1,2,3]
// 3. ES6 新方法
Array.of(1,2,3); // [1,2,3] - 不會有單參數長度陷阱
Array.from('abc'); // ['a','b','c']
Array.from({length: 3}, (_, i) => i * 2); // [0,2,4]
核心增刪改查
| 操作 | 方法 | 備註 |
| 末尾添加 | push() | 返回新長度 |
| 末尾刪除 | pop() | 返回被刪元素 |
| 開頭添加 | unshift() | |
| 開頭刪除 | shift() | |
| 中間增刪 | splice(index, count, ...items) | 原地修改,返回刪除項 |
| 查找索引 | indexOf() / lastIndexOf() | 嚴格相等 === |
| 查找元素 | find(fn) / findIndex(fn) | ES6,回調返回 true |
| 判斷存在 | includes(val) | ES7,支持 NaN |
| 合併 | concat() / [...a, ...b] | 返回新數組 |
| 切片 | slice(start, end) | 不修改原數組 |
高階遍歷與轉換 (ES6+)
var nums = [1, 2, 3, 4, 5];
// 映射
nums.map(x => x * 2); // [2,4,6,8,10]
// 過濾
nums.filter(x => x > 2); // [3,4,5]
// 歸約
nums.reduce((sum, x) => sum + x, 0); // 15
// 查找
nums.find(x => x > 3); // 4
nums.findIndex(x => x > 3); // 3
// 扁平化
[[1,2], [3,4]].flat(); // [1,2,3,4]
// 去重 (ES6)
[...new Set([1,2,2,3])]; // [1,2,3]
類陣列轉真數組
function func() {
// arguments 是類陣列
var args = Array.prototype.slice.call(arguments); // ES5
var args = Array.from(arguments); // ES6
var args = [...arguments]; // ES6 展開運算符
// NodeList 同理
var nodes = Array.from(document.querySelectorAll('div'));
}
避坑指南
- ❌
new Array(3) 創建稀疏數組,map/forEach 會跳過空位
- ❌
for...in 遍歷數組會包含原型鏈屬性和非數字鍵
- ✅ 遍歷用
for...of / forEach / for (let i=0; i
- ✅ 判斷數組用
Array.isArray(arr),typeof [] === 'object'