要將變量強制轉換爲布爾值而不更改其值:javascript
const myBoolean = !! myVariable; !!null // false !!undefined // false !!false // false !!ture // ture !!"" // false !!"string" // true !!0 // false !!1 // true !!{} // true !![] // true
要使用spread運算符有條件地在對象上設置屬性:java
const myObject = {... myProperty && {propName:myPoperty}}; let myProperty = 'Jhon' const myObject = {...myProperty && {propName: myProperty}}; // {propName: "Jhon"} let myProperty = '' const myObject = {...myProperty && {propName: myProperty}}; // {}
若是myProperty結果爲false,則 && 失敗而且不設置新屬性; 不然,若是不爲空,&& 將設置新屬性並覆蓋原來的值。git
const mergedObject = { ...objectOne, ...objectTwo }; const mergedObject = { ...{name: 'Jhon', age: '18'}, ...{name1: 'jhon1', age1: '12'}}; // {name: "Jhon", age: "18", name1: "jhon1", age1: "12"} const mergedObject = { ...{name: 'Jhon', age: '18'}, ...{name: 'jhon1', age:'12'}}; // {name: "jhon1", age: "12"}
支持無限制合併,但若是對象之間存在相同屬性,則後面屬性會覆蓋前面屬性。*請注意,這僅適用於淺層合併。github
要在不使用中間變量的狀況下交換兩個變量的值:web
[varA,varB] = [varB,varA]; let a = 1; let b = 2; [a, b] = [b, a] // a = 2 b = 1
const clean = dirty.filter(Boolean); const clean = [0, false, true, undefined, null, '', 12, 15].filter(Boolean); // [true, 12, 15]
這將刪除值等於:null,undefined,false,0 和空字符串('')。正則表達式
要將Number元素轉換爲String元素:數組
const stringArray = numberArray.map(String); const stringArray = [1, 2, 3].map(String); ["1", "2", "3"]
若是數組包含字符串,字符串原樣保留。 這也能夠用於將String元素轉換爲Number類型:app
const numberArray = stringArray.map(Number); const stringArray = ["1", "2", "3"].map(String); // [1, 2, 3]
要以可讀的格式顯示JSON代碼:dom
const formatted = JSON.stringify(myObj, null, 4); const formatted = JSON.stringify({name: 'Jhon', age: 18, address: 'sz'}, null, 4); /* { "name": "Jhon", "age": 18, "address": "sz" } */
該字符串化命令有三個參數。第一個是Javascript對象。第二個是可選函數,可用於在JSON進行字符串化時對其執行操做。最後一個參數指示要添加多少空格做爲縮進以格式化JSON。省略最後一個參數,JSON將返回一個長行。若是myObj中存在循環引用,則會格式失敗。函數
要建立一個數組並用數字填充它,索引爲零:
const numArray = Array.from(new Array(10), (x, i)=> i); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const code = Math.floor(Math.random() * 1000000).toString().padStart(6, "0"); // 942377
const IDReg= /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$)/;
有時候咱們會對url的查詢參數即從問號 (?)後 開始的 URL(查詢部分)進行轉換
const searchObj = search => JSON.parse(`{"${decodeURIComponent(search.substring(1)).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`); // 假如請求url爲 // 'https://www.baidu.com?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=js&rsv_pq=a86b5e5f0007bceb&rsv_t=1e1fAVan%2BVlnkhJHFB0BIGLdLM2slszYMJBTTfFkmyyBUzBpw0ggeuVDE50&rqlang=cn&rsv_enter=0&inputT=1287&rsv_sug3=5&rsv_sug1=3&rsv_sug7=101&rsv_sug2=0&rsv_sug4=1907' // 那麼 window.location.search 就爲: let search = '?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=js&rsv_pq=a86b5e5f0007bceb&rsv_t=1e1fAVan%2BVlnkhJHFB0BIGLdLM2slszYMJBTTfFkmyyBUzBpw0ggeuVDE50&rqlang=cn&rsv_enter=0&inputT=1287&rsv_sug3=5&rsv_sug1=3&rsv_sug7=101&rsv_sug2=0&rsv_sug4=1907' searchObj(search)
格式化查詢字符串獲得以下對象:
const objectToQueryString = (obj) => Object.keys(obj).map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`).join('&'); objectToQueryString({name: 'Jhon', age: 18, address: 'beijing'}) // name=Jhon&age=18&address=beijing
const similarity = (arr, values) => arr.filter(v => values.includes(v)); similarity([1, 2, 3], [1, 2, 4]); // [1,2]
使用正則表達式來檢測 navigator.userAgent 屬性判斷設備是在移動設備仍是在臺式機/筆記本電腦打開。
const detectDeviceType = () =>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop';
const toDecimalMark = num => num.toLocaleString('en-US'); toDecimalMark(12305030388.9087); // "12,305,030,388.909"
const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]
const reducedFilter = (data, keys, fn) =>data.filter(fn).map(el =>keys.reduce((acc, key) => {acc[key] =el[key];return acc;}, {})); const data = [ { id: 1, name: 'john', age: 24 }, { id: 2, name: 'mike', age: 50 } ]; let a = reducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: 'mike'}]
轉換駝峯拼寫的字符串爲特定格式。
使用 String.replace() 去除下劃線,連字符和空格,並將駝峯拼寫格式的單詞轉換爲全小寫。省略第二個參數 separator ,默認使用 _ 分隔符。
const fromCamelCase = (str, separator = '_') =>str.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2').replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2').toLowerCase(); fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name' fromCamelCase('someLabelThatNeedsToBeCamelized', '-'); // 'some-label-that-needs-to-be-camelized' fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property'
const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str); isAbsoluteURL('https://google.com'); // true isAbsoluteURL('ftp://www.myserver.net'); // true isAbsoluteURL('/foo/bar'); // false
20.獲取兩個日期相差天數
const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24); getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9
const deDupe = (myArray) => [... new Set(myArray)]; deDupe([1, 1, 2, 1, 3, 3, 4]) // [1, 2, 3, 4]
const uniqueElementsBy = (arr, fn) =>arr.reduce((acc, v) => {if (!acc.some(x => fn(v, x))) acc.push(v);return acc;}, []); uniqueElementsBy([{id: 1, name: 'Jhon'}, {id: 2, name: 'sss'}, {id: 1, name: 'Jhon'}], (a, b) => a.id == b.id) // [{id: 1, name: 'Jhon'}, {id: 2, name: 'sss'}]
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); RGBToHex(255, 165, 1); // 'ffa501'
const passwordReg = /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?]{8,20}$/; // -長度8~20位字符,支持大小寫字母、數字、符號三種字符中任意兩種字符的組合
const hasClass = (el, className) => new RegExp(`(^|\\s)${className}(\\s|$)`).test(el.className);
參考資料:
30-seconds-of-code
做者:alentan
連接:https://juejin.im/post/5d01bd04f265da1b7a4b6e03