JavaScript 是一種函數式程式語言,函數起著至關重要的作用。它們允許您封裝可重複使用程式碼並執行特定任務。以下是一些可以讓您的生活更輕鬆的功能的快速範例:
常規功能
function sum(a, b) { return a + b; }
函數表達式
const sum = function (a, b) { return a + b; };
箭頭函數
const sum = (a, b) => { return a + b; }; // OR const sum = (a, b) => a + b;
生成器函數
function* indexGenerator() { let index = 0; while (true) { yield index++; } } const g = indexGenerator(); console.log(g.next().value); // => 0 console.log(g.next().value); // => 1
建立一個從 1 到 n 的數字數組
const range = (n) => Array.from({ length: n }, (_, i) => i + 1); console.log(range(10)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
依步驟建立一個從 1 到 n 的數字數組
const range = (n, step = 1) => Array.from({ length: n }, (_, i) => i * step); console.log(range(10, 2)); // [1, 3, 5, 7, 9]
建立一個陣列並用值填滿它
const fill = (len, value) => Array(len).fill(value); console.log(fill(3, 0)); // [0, 0, 0]
打亂數組
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random()); console.log(shuffleArray([1, 2, 3, 4])); // [3, 2, 1, 4]
從陣列中刪除重複項
const removeDuplicated = (arr) => [...new Set(arr)]; console.log(removeDuplicated([1, 2, 3, 3, 4, 4, 5, 5, 6])); // Result: [ 1, 2, 3, 4, 5, 6 ] // OR const removeDuplicate = (arr) => Object.values(arr.reduce((a, b) => (a[b] ? a : { ...a, [b]: b }), {})); console.log(removeDuplicate([1, 2, 3, 3])); // Result: [ 1, 2, 3, ]
產生隨機數
const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; console.log(random(1, 10)); // Result: 1 ~ 10
找出最大的數字
const findLargest = (arr) => arr.map((subArr) => Math.max(...subArr)); console.log( findLargest([ [4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1], ]) ); // [5, 27, 39, 1001]
找出最小的數字
const findSmallest = (arr) => arr.map((subArr) => Math.min(...subArr)); console.log( findSmallest([ [4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1], ]) ); // [1, 18, 32, 857]
從陣列中隨機選取一個元素
const pick = (arr) => arr[Math.floor(Math.random() * arr.length)]; console.log(pick([1, 2, 3, 4])); // 2
將陣列轉換為物件
const toObject = (arr) => ({ ...arr }); console.log(toObject(["a", "b"])); // { 0: 'a', 1: 'b' }
求兩個陣列的交集
const intersection = (arr1, arr2) => { const set = new Set(arr1); return arr2.filter((x) => set.has(x)); }; console.log(intersection([1, 2, 3], [2, 3, 4])); // [2, 3]
從陣列中刪除虛假值
const compact = (arr) => arr.filter(Boolean); console.log(compact([0, 1, false, 2, "", 3, "a", "e" * 23, NaN, "s", 34])); // [1, 2, 3, 'a', 's', 34]
反轉字串
const reverseString = (str) => str.split("").reverse().join(""); console.log(reverseString("hello")); // olleh
字串是回文
const isPalindrome = (str) => str === str.split("").reverse().join(""); console.log(isPalindrome("madam")); // true
檢查物件是否為空
const isEmpty = (obj) => Object.keys(obj).length === 0; console.log(isEmpty({})); // true
找出一個月中的天數
const getDaysInMonth = (date) => new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate(); console.log(getDaysInMonth(new Date())); // 31
產生隨機顏色
const getRandomColor = () => `#${Math.floor(Math.random() * 16777215).toString(16)}`; console.log(getRandomColor()); // #f0f0f0 // OR const randomHex = () => `#${Math.floor(Math.random() * 0xffffff) .toString(16) .padEnd(6, "0")}`; console.log(randomHex()); // #f0f0f0
查看 Javascript Quick Functions GitHub 儲存庫以了解更多此類函數。
以上是JavaScript 函數可簡化您的程式碼 | JavaScript 函數 | JavaScript 教程的詳細內容。更多資訊請關注PHP中文網其他相關文章!