JavaScript開發小技巧

總結一些可以提升開發效率的JS技巧數組

一、過濾惟一值數據結構

Set類型是在ES6中新增的,它相似於數組,可是成員的值都是惟一的,沒有重複的值。結合擴展運算符(...)咱們能夠建立一個新的數組,達到過濾原數組重複值的功能。url

const array2 = [1, 2, 3, 3, 5, 5, 1];
const uniqueArray = [...new Set(array2)];
console.log(uniqueArray); // [1, 2, 3, 5]

二、轉換Number類型spa

let testInt = "12";
testInt = +testInt;
console.log(testInt); // Result: 12

三、截取數組,若是你知道原始數組的長度,就能夠經過從新定義它的length屬性來實現截取。3d

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array.length = 4;
console.log(array); // Result: [0, 1, 2, 3]

slice()方法的運行時更快。若是速度是你的主要目標,考慮使用下面的方式。code

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.slice(0, 4);
console.log(array); // Result: [0, 1, 2, 3]

四、獲取數組中的最後的元素,數組方法slice()能夠接受負整數,若是提供它,它將從數組的末尾開始截取數值,而不是開頭。orm

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(array.slice(-1)); // Result: [9]
console.log(array.slice(-2)); // Result: [8, 9]
console.log(array.slice(-3)); // Result: [7, 8, 9]

五、是否爲質數blog

const mathIsPrime = n => {
  if (n === 2 || n === 3) {
    return true
  }
  if (isNaN(n) || n <= 1 || n % 1 != 0 || n % 2 == 0 || n % 3 == 0) {
    return false;
  }
  for (let x = 6; x <= Math.sqrt(n) + 1; x += 6) {
    if (n % (x - 1) == 0 || n % (x + 1) == 0) {
      return false
    }
  }
  return true
}
mathIsPrime(0) // false

六、RGB色值生成16進制色值ip

const rgb2Hex = (r, g, b) => {
    r = Math.max(Math.min(Number(r), 100), 0) * 2.55
    g = Math.max(Math.min(Number(g), 100), 0) * 2.55
    b = Math.max(Math.min(Number(b), 100), 0) * 2.55
    r = ('0' + (Math.round(r) || 0).toString(16)).slice(-2)
    g = ('0' + (Math.round(g) || 0).toString(16)).slice(-2)
    b = ('0' + (Math.round(b) || 0).toString(16)).slice(-2)
    return '#' + r + g + b
}
rgb2Hex(100, 50, 0) // "#ff7f00"

七、顏色混合開發

const colourBlend = (c1, c2, ratio) => {
    ratio = Math.max(Math.min(Number(ratio), 1), 0)
    let r1 = parseInt(c1.substring(1, 3), 16)
    let g1 = parseInt(c1.substring(3, 5), 16)
    let b1 = parseInt(c1.substring(5, 7), 16)
    let r2 = parseInt(c2.substring(1, 3), 16)
    let g2 = parseInt(c2.substring(3, 5), 16)
    let b2 = parseInt(c2.substring(5, 7), 16)
    let r = Math.round(r1 * (1 - ratio) + r2 * ratio)
    let g = Math.round(g1 * (1 - ratio) + g2 * ratio)
    let b = Math.round(b1 * (1 - ratio) + b2 * ratio)
    r = ('0' + (r || 0).toString(16)).slice(-2)
    g = ('0' + (g || 0).toString(16)).slice(-2)
    b = ('0' + (b || 0).toString(16)).slice(-2)
    return '#' + r + g + b
}
colourBlend('#ff0000', '#3333ff', 0.5) // "#991a80"

八、時間格式化

const dateFormatter = (formatter, date) => {
    date = (date ? new Date(date) : new Date)
    const Y = date.getFullYear() + '',
          M = date.getMonth() + 1,
          D = date.getDate(),
          H = date.getHours(),
          m = date.getMinutes(),
          s = date.getSeconds()
    return formatter.replace(/YYYY|yyyy/g, Y)
                    .replace(/YY|yy/g, Y.substr(2, 2))
                    .replace(/MM/g, (M < 10 ? '0' : '') + M)
                    .replace(/DD/g, (D < 10 ? '0' : '') + D)
                    .replace(/HH|hh/g, (H < 10 ? '0' : '') + H)
                    .replace(/mm/g, (m < 10 ? '0' : '') + m)
                    .replace(/ss/g, (s < 10 ? '0' : '') + s)
}

dateFormatter('YYYY-MM-DD HH:mm', '2019/08/30 13:55') // 2019-08-30 13:55

 九、樹形結構數據,已知某一子節點 一次向上獲取全部父節點

/**
 * 已知某一子節點 ,向上獲取全部父節點
 * @param {any} tree 樹形結構數據
 * @param {any} func 判斷條件
 * @param {any} path 返回的默認附加值
 */
function treeFindParents(tree, func, path = []) {
    if (!tree) return []
    for (const data of tree) {
        // 這裏按照你的需求來存放最後返回的內容吧
        path.push(data)
        if (func(data)) return path
        if (data.children) {
            const findChildren = treeFindParents(data.children, func, path)
            if (findChildren.length) return findChildren
        }
        path.pop()
    }
    return []
}

  樹形數據結構:

resData=[
        {
            "parentId": "0",
            "id": "1e89edd7-69a0-4e09-9594-f9c8aac6ea4a",
            "url": "/Purchase/SkuDetail/SkuDetailIndex",
            "name": "首頁",
            "children": [],
            "icon": "icon-hone"
        },
        {
            "parentId": "0",
            "id": "8ee224f7-a995-4e60-b781-147c24a4be2c",
            "url": "#",
            "name": "商品模塊",
            "children": [
                {
                    "parentId": "8ee224f7-a995-4e60-b781-147c24a4be2c",
                    "id": "9c826d2c-bece-470f-b6ae-6bf99e1ade1c",
                    "url": "/Supplier/Product_Spu/EditProduct",
                    "name": "發佈商品",
                    "children": [],
                    "icon": "icon-release-commodities"
                },
                {
                    "parentId": "8ee224f7-a995-4e60-b781-147c24a4be2c",
                    "id": "78de0cff-2327-4a7a-875c-9a6fb0bf2341",
                    "url": "/Supplier/Product_Spu/WaitProducts",
                    "name": "待審覈商品",
                    "children": [],
                    "icon": "icon-Commodities-examined"
                },
                {
                    "parentId": "8ee224f7-a995-4e60-b781-147c24a4be2c",
                    "id": "989e309d-3dcc-4f1d-8230-2c8a72aca90c",
                    "url": "/Supplier/Product_Spu/ProductList",
                    "name": "商品列表",
                    "children": [],
                    "icon": "icon-product-list"
                }
            ],
            "icon": "el-icon-goods"
        },
        {
            "parentId": "0",
            "id": "d77f9a2d-3fd4-49e6-b630-11fa75b89044",
            "url": "#",
            "name": "訂單模塊",
            "children": [
                {
                    "parentId": "d77f9a2d-3fd4-49e6-b630-11fa75b89044",
                    "id": "d856fc34-3333-43d9-a5e0-ee157daaaaa8",
                    "url": "/Purchase/PurchaseOrder/PurchaseOrderIndex",
                    "name": "待接單列表",
                    "children": [],
                    "icon": "icon-Single-received"
                },
                {
                    "parentId": "d77f9a2d-3fd4-49e6-b630-11fa75b89044",
                    "id": "eb3c76af-d9d1-4a30-8ee6-4c2f043c1638",
                    "url": "/Purchase/SkuDetail/SkuDetailToBeShipped",
                    "name": "待發貨列表",
                    "children": [],
                    "icon": "icon-Waiting-list"
                },
                {
                    "parentId": "d77f9a2d-3fd4-49e6-b630-11fa75b89044",
                    "id": "017af012-c59f-4f8c-a8b5-89696a82e7bf",
                    "url": "/Purchase/SkuDetail/SkuDetailShipped",
                    "name": "已發貨列表",
                    "children": [],
                    "icon": "icon-received"
                }
            ],
            "icon": "el-icon-tickets"
        },
        {
            "parentId": "0",
            "id": "d9976bfc-62ad-4f26-893d-9bfbc3efddae",
            "url": "#",
            "name": "帳單模塊",
            "children": [
                {
                    "parentId": "d9976bfc-62ad-4f26-893d-9bfbc3efddae",
                    "id": "e8ce3c6b-7a4b-4be6-95ff-cd00d40a0ba5",
                    "url": "/Bill/BillData/StayConfirmIndex",
                    "name": "待確認帳單",
                    "children": [],
                    "icon": "icon-Single-received"
                },
                {
                    "parentId": "d9976bfc-62ad-4f26-893d-9bfbc3efddae",
                    "id": "ef438e69-2e14-4026-a004-1c723c482a28",
                    "url": "/Bill/BillData/ConfirmedIndex",
                    "name": "已確認帳單",
                    "children": [],
                    "icon": "icon-Confirmed-bill"
                }
            ],
            "icon": "el-icon-menu"
        },
        {
            "parentId": "0",
            "id": "f0bd7551-1338-4e0d-a959-21e893e9eacc",
            "url": "/Home/Index",
            "name": "首頁",
            "children": [
                {
                    "parentId": "f0bd7551-1338-4e0d-a959-21e893e9eacc",
                    "id": "e9431b41-7a86-4d4e-8c33-6ff635381699",
                    "url": "/DashBoard/Introduction/IntroductionIndex",
                    "name": "使用介紹",
                    "children": [],
                    "icon": "el-icon-question"
                },
                {
                    "parentId": "f0bd7551-1338-4e0d-a959-21e893e9eacc",
                    "id": "78935279-4be8-4111-81e3-fe38c91eac4d",
                    "url": "/DashBoard/ShowData/ShowDataIndex",
                    "name": "數據統計",
                    "children": [],
                    "icon": "el-icon-info"
                }
            ],
            "icon": "el-icon-info"
        }
    ]

調用treeFindParents返回結果:

treeFindParents(resData, data=> data.id==='989e309d-3dcc-4f1d-8230-2c8a72aca90c',["888888","7777"]) //返回    ["888888", "7777", "商品模塊", "商品列表"]
相關文章
相關標籤/搜索