萬盛學電腦網

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

JavaScript 數組與循環操作深度解析

數組是 JavaScript 中最基礎、使用頻率最高的數據結構之一。本文系統講解數組的創建、遍歷、隊列/棧模擬、搜索、迭代、過濾等核心操作,並提供 ES5+ 現代 API 與兼容性補丁的對照實現,幫助開發者構建扎實的數組操作知識體系。

數組創建的兩種方式

// 構造函數創建
var arrObject = new Array("val1", "val2");

// 字面量創建(推薦)
var arrLiteral = ["val1", "val2"];

差異點:字面量在函數中每次調用都會重新解析,構造函數則僅創建一次實例。對於引擎優化,字面量通常性能更優;但兩者調用 Array 原型方法無差別。

1. 循環遍歷數組

最經典的 for 循環:

var animals = ["cat", "dog", "whale", "seal"];
var animalString = "";
for (var i = 0; i < animals.length; i++) {
    animalString += animals[i] + " ";
}
alert(animalString);

要點:數組索引從 0 開始,length 屬性動態反映元素數量,循環條件用 i < length 而非 i <= length - 1。

2. 先進先出(FIFO)隊列模擬

使用 push 入隊、shift 出隊:

var queue = [];
queue.push("first");
queue.push("second");
queue.push("third");

alert(queue.shift()); // "first"
alert(queue.shift()); // "second"
alert(queue);         // ["third"]
  • push:在末尾添加元素,返回新長度,原數組長度自增。
  • shift:移除首個元素並返回該值,原數組長度自減,索引重排。

3. 後進先出(LIFO)棧模擬

使用 push 入棧、pop 出棧:

var stack = [];
stack.push("first");
stack.push("second");
stack.push("third");

alert(stack.pop()); // "third"
alert(stack.pop()); // "second"
alert(stack);       // ["first"]

pop 從末尾取出元素,同樣修改原數組長度。

4. 數組搜索:indexOf / lastIndexOf

ES5 正式標準化,返回首次/最後一次匹配的索引,未找到返回 -1:

var animals = ["dog", "cat", "seal", "elephant", "lion"];
animals.indexOf("elephant");    // 3
animals.indexOf("seal", 2);     // 2,從索引2開始搜
animals.lastIndexOf("cat");     // 1

舊環境兼容性補丁

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt, from) {
        var len = this.length >>> 0;
        from = Number(from) || 0;
        from = (from < 0) ? Math.ceil(from) : Math.floor(from);
        if (from < 0) from += len;
        for (; from < len; from++) {
            if (from in this && this[from] === elt) return from;
        }
        return -1;
    };
}

5. forEach:對每個元素執行回調

不返回新數組,適用於副作用操作(如修改原數組、日誌記錄):

function replaceElement(element, index, array) {
    if (element === "ab") array[index] = "**";
}
var charSets = ["ab", "bb", "cd", "ab", "cc", "ab", "dd", "ab"];
charSets.forEach(replaceElement);
alert(charSets); // **,bb,cd,**,cc,**,dd,**

兼容性補丁

if (!Array.prototype.forEach) {
    Array.prototype.forEach = function(fun, thisp) {
        var len = this.length >>> 0;
        if (typeof fun !== "function") throw new TypeError();
        for (var i = 0; i < len; i++) {
            if (i in this) fun.call(thisp, this[i], i, this);
        }
    };
}

6. filter:創建過濾後的新數組

返回所有通過測試函數的元素組成的新數組,原數組不變:

function removeChars(element) {
    return element !== "**";
}
var charSets = ["**", "bb", "cd", "**", "cc", "**", "dd", "**"];
var filtered = charSets.filter(removeChars);
alert(filtered); // ["bb", "cd", "cc", "dd"]

總結與最佳實踐

  • 優先使用字面量 [] 創建數組。
  • 遍歷首選 forEach、map、filter 等函數式方法,代碼更聲明式、可讀性強。
  • 需修改原數組時用 push/pop/shift/unshift/splice;需生成新數組用 map/filter/reduce。
  • 舊瀏覽器環境務必引入 Polyfill(如 core-js 或手寫補丁),確保 ES5+ API 可用。

熟練掌握這些 API,能讓數據處理邏輯更清晰、維護成本更低,是前端工程師必備的基本功。

copyright © 萬盛學電腦網 all rights reserved