| 分類 | 函數 | 用途 | 現代原生替代 |
|---|---|---|---|
| 物件/通用迭代 | $.each(obj, fn) | 遍歷物件屬性或陣列元素 | Object.entries(), for...of, Array.forEach() |
$.extend(target, ...sources) | 合併物件 (深/淺拷貝) | Object.assign(), {...obj1, ...obj2}, structuredClone() (深拷貝) | |
| 陣列操作 | $.grep(arr, fn, invert) | 過濾陣列 (invert 反向) | arr.filter() |
$.map(arr, fn) | 映射轉換陣列 (扁平化) | arr.map(), arr.flatMap() | |
$.inArray(val, arr) | 查找值索引 (-1 不存在) | arr.indexOf(), arr.findIndex() | |
$.uniqueSort(arr) | 去重排序 (DOM 元素專用) | [...new Set(arr)], arr.filter((v,i,a)=>a.indexOf(v)===i) | |
| 字串 | $.trim(str) | 去除首尾空白 | str.trim() |
| 腳本載入 | $.getScript(url, cb) | 動態載入 JS | import(), <script type="module"> |
| 衝突處理 | $.noConflict() | 釋放 $ 變數控制權 | 模組化/IIFE 避免衝突 |
| 類型檢查 | $.type(), $.isArray(), $.isPlainObject(), $.isFunction(), $.isNumeric(), $.isWindow() | 類型判斷 | typeof, Array.isArray(), Object.prototype.toString.call() |
// 陣列
$.each([10, 20, 30], function(index, value) {
console.log(index, value); // 0 10, 1 20, 2 30
if (value === 20) return false; // 相當於 break
// return true 相當於 continue
});
// 物件
$.each({ name: 'John', age: 30 }, function(key, value) {
console.log(key, value); // name John, age 30
});
// DOM 元素集合
$('li').each(function(i, el) {
console.log(i, el.innerText);
});
// 淺拷貝 (預設)
var target = { a: 1, b: { x: 10 } };
var source = { b: { y: 20 }, c: 30 };
$.extend(target, source);
// target = { a:1, b:{y:20}, c:30 } // b.x 遺失!淺拷貝只合併第一層
// 深拷貝 (deep = true)
var target2 = { a: 1, b: { x: 10 } };
$.extend(true, target2, { b: { y: 20 }, c: 30 });
// target2 = { a:1, b:{x:10, y:20}, c:30 } // 深度合併保留 b.x
// 建立新物件不污染來源
var merged = $.extend(true, {}, defaultOptions, userOptions);
var numbers = [1, 2, 3, 4, 5, 6];
var evens = $.grep(numbers, function(n) { return n % 2 === 0; });
// [2, 4, 6]
var odds = $.grep(numbers, function(n) { return n % 2 === 0; }, true); // invert=true
// [1, 3, 5]
var users = [{name:'A', roles:['admin']}, {name:'B', roles:['user','editor']}];
// 扁平化:取得所有角色
var allRoles = $.map(users, function(user) {
return user.roles; // 回傳陣列會被扁平化
});
// ["admin", "user", "editor"]
// 物件映射 (jQuery 會轉為陣列處理)
var lengths = $.map({a: 'foo', b: 'bar'}, function(v, k) {
return k + ':' + v.length;
});
// ["a:3", "b:3"]
var colors = ['red', 'green', 'blue'];
$.inArray('green', colors); // 1
$.inArray('yellow', colors); // -1
// 等同於
colors.indexOf('green'); // 1
// 但 $.inArray 內部優化了針對陣列的查找
$.trim(' hello world '); // "hello world"
// 等同 ' hello world '.trim()
$.getScript('https://cdn.example.com/library.js')
.done(function(script, textStatus) {
console.log('載入成功', textStatus);
// library 已可用
})
.fail(function(jqxhr, settings, exception) {
console.error('載入失敗', exception);
});
// $.each(obj, fn)
Object.entries(obj).forEach(([key, val]) => { ... });
arr.forEach((val, idx) => { ... });
// $.extend(true, {}, ...sources)
const merged = { ...obj1, ...obj2 }; // 淺層
const deepMerged = structuredClone(obj1); // 深拷貝 (現代瀏覽器)
// 或使用 lodash.merge / deepmerge 套件
// $.grep(arr, fn)
const filtered = arr.filter(fn);
const filteredInverse = arr.filter(v => !fn(v));
// $.map(arr, fn)
const mapped = arr.map(fn);
const flatMapped = arr.flatMap(fn); // 扁平化
// $.inArray(val, arr)
const idx = arr.indexOf(val);
const idxObj = arr.findIndex(obj => obj.id === val);
// $.trim(str)
const trimmed = str.trim();
// $.getScript(url)
const module = await import(url); // ES Module
// 或動態建立 script 標籤 (非模組)
function loadScript(url) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = url;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
// $.noop
const noop = () => {};
// $.now()
const now = Date.now();
// $.proxy(fn, ctx)
const bound = fn.bind(ctx); // 箭頭函數自動綁定 this
// 類型檢查
Array.isArray(arr);
typeof val === 'function';
typeof val === 'number' && !isNaN(val); // isNumeric
Object.prototype.toString.call(val) === '[object Object]'; // isPlainObject
$.each 回調函數內 this 指向當前值 (原始值會被包裝成物件),箭頭函數無 this。$.extend(true, ...) 深拷貝會遞歸,**循環參考會導致堆疊溢位**,structuredClone 可處理循環參考。$.map 回傳陣列會自動扁平化,回傳 null/undefined 會被過濾掉。for 迴圈或 for...of,避免函數呼叫開銷。jQuery 工具函數在 ES5 時代填補了 JS 標準庫空缺。**現代環境 (ES2015+) 幾乎全部有原生對應且效能更好**。遷移策略:
structuredClone 或 lodash。import() (模組) 或 Promise 封裝 <script>。