您可以在 repo Github 上找到這篇文章中的所有程式碼。
陣列相關的挑戰
陣列
/** * @return {Array} */ function arrayOf(arr) { return [].slice.call(arguments); } // Usage example const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const combinedArray = arrayOf(array1, array2); console.log(combinedArray); // => [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]
數組到樹
/** * @param {Array} arr * @return {Array} */ function arrToTree(arr) { const tree = []; const hashmap = new Map(); // create nodes and store references arr.forEach((item) => { hashmap[item.id] = { id: item.id, name: item.name, children: [], }; }); // build the tree arr.forEach((item) => { if (item.parentId === null) { tree.push(hashmap[item.id]); } else { hashmap[item.parentId].children.push(hashmap[item.id]); } }); return tree; } // Usage example const flatArray = [ { id: 1, name: "Node 1", parentId: null }, { id: 2, name: "Node 1.1", parentId: 1 }, { id: 3, name: "Node 1.2", parentId: 1 }, { id: 4, name: "Node 1.1.1", parentId: 2 }, { id: 5, name: "Node 2", parentId: null }, { id: 6, name: "Node 2.1", parentId: 5 }, { id: 7, name: "Node 2.2", parentId: 5 }, ]; const tree = arrToTree(flatArray); console.log(tree); // => [{ id: 1, name: 'Node 1', children: [ [Object], [Object] ] }, { id: 5, name: 'Node 2', children: [ [Object], [Object] ] }]
數組包裝器
class ArrayWrapper { constructor(arr) { this._arr = arr; } valueOf() { return this._arr.reduce((sum, num) => sum + num, 0); } toString() { return `[${this._arr.join(",")}]`; } } // Usage example const obj1 = new ArrayWrapper([1, 2]); const obj2 = new ArrayWrapper([3, 4]); console.log(obj1 + obj2); // => 10 console.log(String(obj1)); // => [1,2]
類別數組到數組
/** * @param {any} arrayLike * @return {Array} */ function arrayLikeToArray(arrayLike) { return Array.from(arrayLike); } // Usage example const arrayLike = { 0: "a", 1: "b", 2: "c", length: 3, }; console.log(arrayLikeToArray(arrayLike)); // => ['a', 'b', 'c']
區塊
/** * @template T * @param {Array<t>} arr The array to process. * @param {number} [size=1] The length of each chunk. * @returns {Array<array>>} The new array of chunks. */ function chunk(arr, size = 1) { if (!Array.isArray(arr) || size [['a'], ['b'], ['c'], ['d']] console.log(chunk([1, 2, 3, 4], 2)); // => [[1, 2], [3, 4]] console.log(chunk([1, 2, 3, 4], 3)); // => [[1, 2, 3], [4]] </array></t>
組合
/** * @param {array} arrs * @return {array} */ function generateCombinations(arrs) { const result = []; function backtrack(start, current) { if (start === arrs.length) { result.push(current.join('')); return; } for (const item of arrs[start]) { current.push(item); backtrack(start + 1, current); current.pop(); } } backtrack(0, []); return result; } // Usage example const nestedArray = [['a', 'b'], [1, 2], [3, 4]]; console.log(generateCombinations(nestedArray)); // => ['a13', 'a14', 'a23', 'a24', 'b13', 'b14', 'b23', 'b24']
不同之處
/** * @param {Array} array * @param {Array} values * @return {Array} */ function difference(arr, values) { const newArray = []; const valueSet = new Set(values); for (let i = 0; i [1] console.log(difference([1, 2, 3, 4], [2, 3, 1])); // => [4] console.log(difference([1, 2, 3], [2, 3, 1, 4])); // => [] console.log(difference([1, , 3], [1])); // => [3]
立即下降
/** * @param {Array} array * @param {Function} predicate * @return {Array} */ function dropRightWhile(arr, predicate) { let index = arr.length - 1; while (index >= 0 && predicate(arr[index], index, arr)) { index -= 1; } return arr.slice(0, index + 1); } // Usage example console.log(dropRightWhile([1, 2, 3, 4, 5], (value) => value > 3)); // => [1, 2, 3] console.log(dropRightWhile([1, 2, 3], (value) => value [] console.log(dropRightWhile([1, 2, 3, 4, 5], (value) => value > 6)); // => [1, 2, 3, 4, 5]
掉落時
/** * @param {Array} array * @param {Function} predicate * @return {Array} */ function dropWhile(arr, predicate) { let index = 0; while (index value [3, 4, 5] dropWhile([1, 2, 3], (value) => value []
展平
/** * @param {Array} value * @return {Array} */ function flatten(arr) { const newArray = []; const copy = [...arr]; while (copy.length) { const item = copy.shift(); if (Array.isArray(item)) { copy.unshift(...item); } else { newArray.push(item); } } return newArray; } // Usage example console.log(flatten([1, 2, 3])); // [1, 2, 3] // Inner arrays are flattened into a single level. console.log(flatten([1, [2, 3]])); // [1, 2, 3] console.log( flatten([ [1, 2], [3, 4], ]) ); // [1, 2, 3, 4] // Flattens recursively. console.log(flatten([1, [2, [3, [4, [5]]]]])); // [1, 2, 3, 4, 5]
產生唯一的隨機數組
/** * @param {number} range * @param {number} outputCount * @return {Array} */ function generateUniqueRandomArray(range, outputCount) { const arr = Array.from({ length: range }, (_, i) => i + 1); const result = []; for (let i = 0; i [3, 7, 1, 9, 5]
交叉點
/** * @param {Function} iteratee * @param {Array[]} arrays * @returns {Array} */ function intersectionBy(iteratee, ...arrs) { if (!arrs.length) { return []; } const mappedArrs = arrs.map((arr) => arr.map(iteratee)); let intersectedValues = mappedArrs[0].filter((value) => { return mappedArrs.every((mappedArr) => mappedArr.includes(value)); }); intersectedValues = intersectedValues.filter((value, index, self) => { return self.indexOf(value) === index; }); return intersectedValues.map((value) => { const index = mappedArrs[0].indexOf(value); return arrs[0][index]; }); } // Usage example const result = intersectionBy(Math.floor, [1.2, 2.4], [2.5, 3.6]); // => [2.4] console.log(result); // => [2.4] const result2 = intersectionBy( (str) => str.toLowerCase(), ["apple", "banana", "ORANGE", "orange"], ["Apple", "Banana", "Orange"] ); console.log(result2); // => ['apple', 'banana', 'ORANGE']
路口
/** * @param {Array<unknown>[]} arrays - The arrays to find the intersection of. * @returns {Array<unknown>} - An array containing the elements common to all input arrays. */ function intersectArrays(...arrs) { if (!arrs.length) { return []; } const set = new Set(arrs[0]); for (let i = 1; i { if (!arrs[i].includes(value)) { set.delete(value); } }); } return Array.from(set); } // Usage example console.log(intersectArrays([1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 6])); // => [3, 4] </unknown></unknown>
意思是
/** * @param {Array} array * @return {Number} */ function mean(arr) { return arr.reduce((sum, number) => sum + number, 0) / arr.length; } // Usage example console.log(mean([1, 2, 3])); // => 2 console.log(mean([1, 2, 3, 4, 5])); // => 3
刪除重複項
/** * @param {*} arr */ function removeDuplicates(arr) { return Array.from(new Set(arr)); } // Usage example const inputArray = [1, 2, 3, 2, 1, 4, 5, 6, 5, 4]; const outputArray = removeDuplicates(inputArray); console.log(outputArray); // => [1, 2, 3, 4, 5, 6]
隨機播放
/** * @param {any[]} arr * @returns {void} */ function shuffle(arr) { if (arr.length [*, *, *, *]
排序方式
/** * @param {Array} arr * @param {Function} fn * @return {Array} */ function sortBy(arr, fn) { return arr.sort((a, b) => fn(a) - fn(b)); } // Usage example console.log(sortBy([5, 4, 1, 2, 3], (x) => x)); // => [1, 2, 3, 4, 5]
樹到數組
/** * @param {Array} tree * @param {number} parentId * @return {Array} */ function treeToArr(tree, parentId = null) { const arr = []; tree.forEach((node) => { const { id, name } = node; arr.push({ id, name, parentId }); // recursive if (node.children && node.children.length > 0) { arr.push(...treeToArr(node.children, id)); } }); return arr; } // Usage example const tree = [ { id: 1, name: "Node 1", children: [ { id: 2, name: "Node 1.1", children: [ { id: 4, name: "Node 1.1.1", children: [], }, ], }, { id: 3, name: "Node 1.2", children: [], }, ], }, { id: 5, name: "Node 2", children: [ { id: 6, name: "Node 2.1", children: [], }, { id: 7, name: "Node 2.2", children: [], }, ], }, ]; const flatArray = treeToArr(tree); console.log(flatArray); /* [ { id: 1, name: 'Node 1', parentId: null }, { id: 2, name: 'Node 1.1', parentId: 1 }, { id: 4, name: 'Node 1.1.1', parentId: 2 }, { id: 3, name: 'Node 1.2', parentId: 1 }, { id: 5, name: 'Node 2', parentId: null }, { id: 6, name: 'Node 2.1', parentId: 5 }, { id: 7, name: 'Node 2.2', parentId: 5 } ] */
參考
- 2695。數組包裝器 - LeetCode
- 2677。區塊數組 - LeetCode
- 2724。排序依據 - LeetCode
- 2625。展平深度嵌套數組 - LeetCode
- 131。實作 _.chunk() - BFE.dev
- 8.你能 shuffle() 一個陣列嗎? - BFE.dev
- 384。隨機排列數組 - LeetCode
- 138。兩個排序數組的交集 - BFE.dev
- 167。未排序數組的交集 - BFE.dev
- 66。從陣列中刪除重複項 - BFE.dev
以上是陣列 - JavaScript 挑戰的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

JavaScript在現實世界中的應用包括服務器端編程、移動應用開發和物聯網控制:1.通過Node.js實現服務器端編程,適用於高並發請求處理。 2.通過ReactNative進行移動應用開發,支持跨平台部署。 3.通過Johnny-Five庫用於物聯網設備控制,適用於硬件交互。

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

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


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

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