JavaScript 數組方法背後的演算法
JavaScript 陣列方法背後的演算法。
JavaScript 陣列附帶各種內建方法,允許操作和檢索陣列中的資料。以下是從大綱中提取的數組方法列表:
- concat()
- 加入()
- 填充()
- 包括()
- indexOf()
- 反向()
- 排序()
- 拼接()
- 在()
- copyWithin()
- 平()
- Array.from()
- findLastIndex()
- forEach()
- 每個()
- 條目()
- 值()
- toReversed()(建立陣列的反向副本而不修改原始陣列)
- toSorted()(建立陣列的排序副本而不修改原始陣列)
- toSpliced()(建立一個新數組,新增或刪除元素,而不修改原始數組)
- with()(傳回替換了特定元素的陣列副本)
- Array.fromAsync()
- Array.of()
- 地圖()
- flatMap()
- 減少()
- reduceRight()
- 一些()
- 查找()
- findIndex()
- findLast()
讓我分解每個 JavaScript 陣列方法所使用的常用演算法:
1. concat()
- 演算法:線性追加/合併
- 時間複雜度:O(n),其中 n 是所有陣列的總長度
- 內部使用迭代來建立新數組並複製元素
// concat() Array.prototype.myConcat = function(...arrays) { const result = [...this]; for (const arr of arrays) { for (const item of arr) { result.push(item); } } return result; };
2. 加入()
- 演算法:字串連接的線性遍歷
- 時間複雜度:O(n)
- 迭代數組元素並建立結果字串
// join() Array.prototype.myJoin = function(separator = ',') { let result = ''; for (let i = 0; i < this.length; i++) { result += this[i]; if (i < this.length - 1) result += separator; } return result; };
3. 填充()
- 演算法:帶賦值的線性遍歷
- 時間複雜度:O(n)
- 帶有賦值的簡單迭代
// fill() Array.prototype.myFill = function(value, start = 0, end = this.length) { for (let i = start; i < end; i++) { this[i] = value; } return this; };
4. 包含()
- 演算法:線性搜尋
- 時間複雜度:O(n)
- 順序掃描直到找到元素或到達結束
// includes() Array.prototype.myIncludes = function(searchElement, fromIndex = 0) { const startIndex = fromIndex >= 0 ? fromIndex : Math.max(0, this.length + fromIndex); for (let i = startIndex; i < this.length; i++) { if (this[i] === searchElement || (Number.isNaN(this[i]) && Number.isNaN(searchElement))) { return true; } } return false; };
5.indexOf()
- 演算法:線性搜尋
- 時間複雜度:O(n)
- 從開始順序掃描直到找到匹配
// indexOf() Array.prototype.myIndexOf = function(searchElement, fromIndex = 0) { const startIndex = fromIndex >= 0 ? fromIndex : Math.max(0, this.length + fromIndex); for (let i = startIndex; i < this.length; i++) { if (this[i] === searchElement) return i; } return -1; };
6. 反向()
- 演算法:兩個指標交換
- 時間複雜度:O(n/2)
- 從開始/結束向內移動元素
// reverse() Array.prototype.myReverse = function() { let left = 0; let right = this.length - 1; while (left < right) { // Swap elements const temp = this[left]; this[left] = this[right]; this[right] = temp; left++; right--; } return this; };
7. 排序()
- 演算法:通常為 TimSort(合併排序和插入排序的混合)
- 時間複雜度:O(n log n)
- 現代瀏覽器使用自適應排序演算法
// sort() Array.prototype.mySort = function(compareFn) { // Implementation of QuickSort for simplicity // Note: Actual JS engines typically use TimSort const quickSort = (arr, low, high) => { if (low < high) { const pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } }; const partition = (arr, low, high) => { const pivot = arr[high]; let i = low - 1; for (let j = low; j < high; j++) { const compareResult = compareFn ? compareFn(arr[j], pivot) : String(arr[j]).localeCompare(String(pivot)); if (compareResult <= 0) { i++; [arr[i], arr[j]] = [arr[j], arr[i]]; } } [arr[i + 1], arr[high]] = [arr[high], arr[i + 1]]; return i + 1; }; quickSort(this, 0, this.length - 1); return this; };
8. 拼接()
- 演算法:線性數組修改
- 時間複雜度:O(n)
- 就地移動元素並修改數組
// splice() Array.prototype.mySplice = function(start, deleteCount, ...items) { const len = this.length; const actualStart = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); const actualDeleteCount = Math.min(Math.max(deleteCount || 0, 0), len - actualStart); // Store deleted elements const deleted = []; for (let i = 0; i < actualDeleteCount; i++) { deleted[i] = this[actualStart + i]; } // Shift elements if necessary const itemCount = items.length; const shiftCount = itemCount - actualDeleteCount; if (shiftCount > 0) { // Moving elements right for (let i = len - 1; i >= actualStart + actualDeleteCount; i--) { this[i + shiftCount] = this[i]; } } else if (shiftCount < 0) { // Moving elements left for (let i = actualStart + actualDeleteCount; i < len; i++) { this[i + shiftCount] = this[i]; } } // Insert new items for (let i = 0; i < itemCount; i++) { this[actualStart + i] = items[i]; } this.length = len + shiftCount; return deleted; };
9. 在()
- 演算法:直接索引存取
- 時間複雜度:O(1)
- 帶有邊界檢查的簡單數組索引
// at() Array.prototype.myAt = function(index) { const actualIndex = index >= 0 ? index : this.length + index; return this[actualIndex]; };
10. 複製()
- 演算法:區塊記憶體複製
- 時間複雜度:O(n)
- 記憶體複製與移位操作
// copyWithin() Array.prototype.myCopyWithin = function(target, start = 0, end = this.length) { const len = this.length; let to = target < 0 ? Math.max(len + target, 0) : Math.min(target, len); let from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); let final = end < 0 ? Math.max(len + end, 0) : Math.min(end, len); const count = Math.min(final - from, len - to); // Copy to temporary array to handle overlapping const temp = new Array(count); for (let i = 0; i < count; i++) { temp[i] = this[from + i]; } for (let i = 0; i < count; i++) { this[to + i] = temp[i]; } return this; };
11. 平()
- 演算法:遞歸深度優先遍歷
- 時間複雜度:單層為 O(n),深度 d 為 O(d*n)
- 遞歸展平巢狀數組
// flat() Array.prototype.myFlat = function(depth = 1) { const flatten = (arr, currentDepth) => { const result = []; for (const item of arr) { if (Array.isArray(item) && currentDepth < depth) { result.push(...flatten(item, currentDepth + 1)); } else { result.push(item); } } return result; }; return flatten(this, 0); };
12. 數組.from()
- 演算法:迭代與複製
- 時間複雜度:O(n)
- 從可迭代建立新數組
// Array.from() Array.myFrom = function(arrayLike, mapFn) { const result = []; for (let i = 0; i < arrayLike.length; i++) { result[i] = mapFn ? mapFn(arrayLike[i], i) : arrayLike[i]; } return result; };
13. 找出最後一個索引()
- 演算法:反向線性搜尋
- 時間複雜度:O(n)
- 從末尾開始順序掃描直到找到匹配項
// findLastIndex() Array.prototype.myFindLastIndex = function(predicate) { for (let i = this.length - 1; i >= 0; i--) { if (predicate(this[i], i, this)) return i; } return -1; };
14. forEach()
- 演算法:線性迭代
- 時間複雜度:O(n)
- 帶有回呼執行的簡單迭代
// forEach() Array.prototype.myForEach = function(callback) { for (let i = 0; i < this.length; i++) { if (i in this) { // Skip holes in sparse arrays callback(this[i], i, this); } } };
15. 每個()
演算法:短路線性掃描
時間複雜度:O(n)
在第一個錯誤條件下停止
// concat() Array.prototype.myConcat = function(...arrays) { const result = [...this]; for (const arr of arrays) { for (const item of arr) { result.push(item); } } return result; };
16. 條目()
- 演算法:迭代器協定實作
- 時間複雜度:建立 O(1),完整迭代 O(n)
- 建立迭代器對象
// join() Array.prototype.myJoin = function(separator = ',') { let result = ''; for (let i = 0; i < this.length; i++) { result += this[i]; if (i < this.length - 1) result += separator; } return result; };
17. 值()
- 演算法:迭代器協定實作
- 時間複雜度:建立 O(1),完整迭代 O(n)
- 為值建立迭代器
// fill() Array.prototype.myFill = function(value, start = 0, end = this.length) { for (let i = start; i < end; i++) { this[i] = value; } return this; };
18. toReversed()
- 演算法:反向迭代複製
- 時間複雜度:O(n)
- 建立新的反轉數組
// includes() Array.prototype.myIncludes = function(searchElement, fromIndex = 0) { const startIndex = fromIndex >= 0 ? fromIndex : Math.max(0, this.length + fromIndex); for (let i = startIndex; i < this.length; i++) { if (this[i] === searchElement || (Number.isNaN(this[i]) && Number.isNaN(searchElement))) { return true; } } return false; };
19. toSorted()
- 演算法:複製然後 TimSort
- 時間複雜度:O(n log n)
- 使用標準排序建立排序副本
// indexOf() Array.prototype.myIndexOf = function(searchElement, fromIndex = 0) { const startIndex = fromIndex >= 0 ? fromIndex : Math.max(0, this.length + fromIndex); for (let i = startIndex; i < this.length; i++) { if (this[i] === searchElement) return i; } return -1; };
20. toSpliced()
- 演算法:修改複製
- 時間複雜度:O(n)
- 建立修改後的副本
// reverse() Array.prototype.myReverse = function() { let left = 0; let right = this.length - 1; while (left < right) { // Swap elements const temp = this[left]; this[left] = this[right]; this[right] = temp; left++; right--; } return this; };
21. 與()
- 演算法:單次修改的淺拷貝
- 時間複雜度:O(n)
- 建立更改了一個元素的副本
// sort() Array.prototype.mySort = function(compareFn) { // Implementation of QuickSort for simplicity // Note: Actual JS engines typically use TimSort const quickSort = (arr, low, high) => { if (low < high) { const pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } }; const partition = (arr, low, high) => { const pivot = arr[high]; let i = low - 1; for (let j = low; j < high; j++) { const compareResult = compareFn ? compareFn(arr[j], pivot) : String(arr[j]).localeCompare(String(pivot)); if (compareResult <= 0) { i++; [arr[i], arr[j]] = [arr[j], arr[i]]; } } [arr[i + 1], arr[high]] = [arr[high], arr[i + 1]]; return i + 1; }; quickSort(this, 0, this.length - 1); return this; };
22. Array.fromAsync()
- 演算法:非同步迭代與收集
- 時間複雜度:O(n) 非同步操作
- 處理承諾與非同步迭代
// splice() Array.prototype.mySplice = function(start, deleteCount, ...items) { const len = this.length; const actualStart = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); const actualDeleteCount = Math.min(Math.max(deleteCount || 0, 0), len - actualStart); // Store deleted elements const deleted = []; for (let i = 0; i < actualDeleteCount; i++) { deleted[i] = this[actualStart + i]; } // Shift elements if necessary const itemCount = items.length; const shiftCount = itemCount - actualDeleteCount; if (shiftCount > 0) { // Moving elements right for (let i = len - 1; i >= actualStart + actualDeleteCount; i--) { this[i + shiftCount] = this[i]; } } else if (shiftCount < 0) { // Moving elements left for (let i = actualStart + actualDeleteCount; i < len; i++) { this[i + shiftCount] = this[i]; } } // Insert new items for (let i = 0; i < itemCount; i++) { this[actualStart + i] = items[i]; } this.length = len + shiftCount; return deleted; };
23. 數組.of()
- 演算法:直接建立陣列
- 時間複雜度:O(n)
- 從參數建立數組
// at() Array.prototype.myAt = function(index) { const actualIndex = index >= 0 ? index : this.length + index; return this[actualIndex]; };
24. 地圖()
- 演算法:變換迭代
- 時間複雜度:O(n)
- 使用轉換後的元素建立新數組
// copyWithin() Array.prototype.myCopyWithin = function(target, start = 0, end = this.length) { const len = this.length; let to = target < 0 ? Math.max(len + target, 0) : Math.min(target, len); let from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); let final = end < 0 ? Math.max(len + end, 0) : Math.min(end, len); const count = Math.min(final - from, len - to); // Copy to temporary array to handle overlapping const temp = new Array(count); for (let i = 0; i < count; i++) { temp[i] = this[from + i]; } for (let i = 0; i < count; i++) { this[to + i] = temp[i]; } return this; };
25. 平面地圖()
- 演算法:地圖展平
- 時間複雜度:O(n*m),其中 m 是平均映射數組大小
- 結合了映射和展平
// flat() Array.prototype.myFlat = function(depth = 1) { const flatten = (arr, currentDepth) => { const result = []; for (const item of arr) { if (Array.isArray(item) && currentDepth < depth) { result.push(...flatten(item, currentDepth + 1)); } else { result.push(item); } } return result; }; return flatten(this, 0); };
26. 減少()
- 演算法:線性累加
- 時間複雜度:O(n)
- 帶回調的順序累加
// Array.from() Array.myFrom = function(arrayLike, mapFn) { const result = []; for (let i = 0; i < arrayLike.length; i++) { result[i] = mapFn ? mapFn(arrayLike[i], i) : arrayLike[i]; } return result; };
27.reduceRight()
- 演算法:反向線性累加
- 時間複雜度:O(n)
- 由右到左累積
// findLastIndex() Array.prototype.myFindLastIndex = function(predicate) { for (let i = this.length - 1; i >= 0; i--) { if (predicate(this[i], i, this)) return i; } return -1; };
28. 一些()
- 演算法:短路線性掃描
- 時間複雜度:O(n)
- 在第一個真實條件下停止
// forEach() Array.prototype.myForEach = function(callback) { for (let i = 0; i < this.length; i++) { if (i in this) { // Skip holes in sparse arrays callback(this[i], i, this); } } };
29. 尋找()
- 演算法:線性搜尋
- 時間複雜度:O(n)
- 順序掃描直到條件滿足
// every() Array.prototype.myEvery = function(predicate) { for (let i = 0; i < this.length; i++) { if (i in this && !predicate(this[i], i, this)) { return false; } } return true; };
30. 尋找索引()
- 演算法:線性搜尋
- 時間複雜度:O(n)
- 順序掃描匹配條件
// entries() Array.prototype.myEntries = function() { let index = 0; const array = this; return { [Symbol.iterator]() { return this; }, next() { if (index < array.length) { return { value: [index, array[index++]], done: false }; } return { done: true }; } }; };
31. 找出最後一個()
- 演算法:反向線性搜尋
- 時間複雜度:O(n)
- 從末尾開始順序掃描
// concat() Array.prototype.myConcat = function(...arrays) { const result = [...this]; for (const arr of arrays) { for (const item of arr) { result.push(item); } } return result; };
我已經提供了您要求的所有 31 種數組方法的完整實作。
?在 LinkedIn 上與我聯絡:
讓我們一起深入了解軟體工程的世界!我定期分享 JavaScript、TypeScript、Node.js、React、Next.js、資料結構、演算法、Web 開發等方面的見解。無論您是想提高自己的技能還是在令人興奮的主題上合作,我都樂意與您聯繫並與您一起成長。
跟我來:Nozibul Islam
以上是JavaScript 數組方法背後的演算法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python和JavaScript開發者的薪資沒有絕對的高低,具體取決於技能和行業需求。 1.Python在數據科學和機器學習領域可能薪資更高。 2.JavaScript在前端和全棧開發中需求大,薪資也可觀。 3.影響因素包括經驗、地理位置、公司規模和特定技能。

實現視差滾動和元素動畫效果的探討本文將探討如何實現類似資生堂官網(https://www.shiseido.co.jp/sb/wonderland/)中�...

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

學習JavaScript不難,但有挑戰。 1)理解基礎概念如變量、數據類型、函數等。 2)掌握異步編程,通過事件循環實現。 3)使用DOM操作和Promise處理異步請求。 4)避免常見錯誤,使用調試技巧。 5)優化性能,遵循最佳實踐。

如何在JavaScript中將具有相同ID的數組元素合併到一個對像中?在處理數據時,我們常常會遇到需要將具有相同ID�...

探索前端中類似VSCode的面板拖拽調整功能的實現在前端開發中,如何實現類似於VSCode...
