萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 操作 JavaScript 物件與陣列工具函數完整速查:$.each、$.extend、$.grep、$.map、$.inArray、$.trim

工具函數分類總覽

分類函數用途現代原生替代
物件/通用迭代$.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)動態載入 JSimport(), <script type="module">
衝突處理$.noConflict()釋放 $ 變數控制權模組化/IIFE 避免衝突
類型檢查$.type(), $.isArray(), $.isPlainObject(), $.isFunction(), $.isNumeric(), $.isWindow()類型判斷typeof, Array.isArray(), Object.prototype.toString.call()

核心函數詳細範例

$.each(obj, callback) - 萬用迭代器

// 陣列
$.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);
});

$.extend(deep, target, ...sources) - 物件合併

// 淺拷貝 (預設)
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);

$.grep(array, callback, invert) - 過濾

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]

$.map(array, callback) - 映射/扁平化

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"]

$.inArray(value, array) - 查找索引

var colors = ['red', 'green', 'blue'];
$.inArray('green', colors); // 1
$.inArray('yellow', colors); // -1

// 等同於
colors.indexOf('green'); // 1
// 但 $.inArray 內部優化了針對陣列的查找

$.trim(str) - 去除空白

$.trim('  hello world  '); // "hello world"
// 等同 '  hello world  '.trim()

$.getScript(url, callback) - 動態載入腳本

$.getScript('https://cdn.example.com/library.js')
    .done(function(script, textStatus) {
        console.log('載入成功', textStatus);
        // library 已可用
    })
    .fail(function(jqxhr, settings, exception) {
        console.error('載入失敗', exception);
    });

現代原生 API 完整對照遷移表

// $.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+) 幾乎全部有原生對應且效能更好**。遷移策略:

  1. 新代碼直接用原生 API。
  2. 舊代碼維護時機會性替換。
  3. 需深拷貝/循環參考處理用 structuredClone 或 lodash。
  4. 動態載入腳本改用動態 import() (模組) 或 Promise 封裝 <script>。
copyright © 萬盛學電腦網 all rights reserved