Nutils-js is a modular, high-performance JavaScript utility library that I’ve packaged.

In front-end development, data processing such as Array, Object, String and Number are often encountered, or performance optimization such as anti-shaking throttling function, or URL parameter processing, type judgment and other operations. In order to improve development efficiency, I extracted and encapsulated these common public methods and published them on NPM. Further updates will be made if a better writing method is available. In addition, if readers have good suggestions or want to contribute to this project, welcome to submit PR for this project, discuss and exchange together.

The installation

$ npm i --save nutils-js
Copy the code

use

const nutils = require('nutils-js')
nutils.multArray([1.2.3].2)
Copy the code

The API documentation

An array of

  • multArrayTwo-dimensional array conversion
  • flattenFlattening an array
  • flattenDeepSpecifies a hierarchical flat array
  • isArrayEqualCheck that the two array entries are equal
  • allEqualCheck that the array items are equal
  • diffArrayIs the onlyarrayThe value of the array
  • haveArrWith commonarrayThe value of the array
  • uniqueArrayArray to heavy
  • uniqueArrayObjectArray objects are deduplicated
  • treeDataGenerate tree structured data
  • ascArrAn array of ascending
  • descArrAn array in descending order
  • shuffleRandom sequence
  • takeArrayIntercepts the element specified at the beginning of the array
  • takeLastArrayIntercepts the last element specified in the array
  • cloneArrayCloned array
  • maxArrayMaximum value in array
  • validArrayRemoves invalid values from arrays

object

  • isObjectEqualCheck that the values of two objects are equal
  • cloneObjectClone object

function

  • debounceFunction image stabilization
  • throttleFunction of the throttle
  • typeFnType judgment
  • calcFnAddition, subtraction, multiplication and division

string

  • isNilValues arenullorundefined
  • padStartMasking string
  • thousandsA semicolon is added to the number every three digits

digital

  • randomNumberSpecifies a range of random integers
  • averageaveraging
  • averageByCheck the equality of the items in the array object
  • aboutEqualAre these two values approximately equal to
  • getLineSizeCalculate the distance between two points
  • sumThe sum of values in an array

The browser

  • copyTextH5 Copies the text
  • getCurrentURLGets the current URL address
  • scrollToTopReturn to the top
  • smoothScrollSmooth scrolling page
  • isCurrentPageIs the current page

The environment

  • isBrowserBrowser or not
  • isWechatBrowserJudge wechat browser or ordinary H5
  • isMobileCheck whether it is a mobile terminal

For future updates, please click on the GitHub repository

If you have any questions or suggestions about this article, please add me to wechat QQLCX55

Making the address

A, arrays,

multArrayTwo-dimensional array conversion

Divide an array into subarrays and form the subarrays into a new array.

multArray(array, count)
Copy the code

parameter

  • arrayAn array to process
  • count = 8The required length of the subarray

The sample

multArray([1.2.3.4.5.6.7].2) = > [[1.2], [3.4], [5.6], [7]]

multArray(['a'.'b'.'c'.'d'].3) = > [['a'.'b'.'c'], ['d']]
Copy the code

The source code

function multArray(arr, count = 8) {
    let pages = []
    arr.forEach((item, index) = > {
        const page = Math.floor(index / count)
        if(! pages[page]) pages[page] = [] pages[page].push(item) })return pages
}
Copy the code

flattenFlattening an array

Split a nested array into an array

flatten(array)
Copy the code

parameter

  • arrayMultilayer nested arrays

The sample

flatten([1[2], [3], [4.5]])

// [1, 2, 3, 4, 5]
Copy the code

The source code

// Flatten the Map method
const flatten = arr= >[].concat(... arr.map(v= > (Array.isArray(v) ? flatten(v) : v)))

// Flatten the Reduce method
const flatten = arr= > arr.reduce((a, c) = > a.concat(Array.isArray(c) ? flatten(c) : c), [])
Copy the code

flattenDeepSpecifies a hierarchical flat array

Splits a multilevel nested array into a specified level array

flattenDeep(array, depth)
Copy the code

parameter

  • arrayMultilayer nested arraysdepth = Reduced number of nesting levels

The sample

flattenDeep([1[2[3[4]], 5]], 1)
// => [1, 2, [3, [4]], 5]

// ES6 method 'flat(depth)'; [1[2[3[4]], 5]].flat(1)
// => [1, 2, [3, [4]], 5]
Copy the code

The source code

const flattenDeep = (arr, depth = 1) = > arr.reduce((a, v) = > a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), [])
Copy the code

isArrayEqualCheck that the two array entries are equal

Returns a Boolean value that compares the values of the items in two arrays

isArrayEqual(array, array)
Copy the code

parameter

  • arrayThe array to check
  • arrayThe array to check

The sample

isArrayEqual([6.5.2.4.1.3], [1.2.3.4.5.6])
// => true

isArrayEqual([6.5.2.7.1.3], [1.2.3.4.5.6])
// => false
Copy the code

The source code

const isArrayEqual = (a, b, has = true) = > {
    if(a.length ! == b.length)return (has = false)
    const s = new Set(b)
    if (a.find(x= >! s.has(x)))return (has = false)
    return has
}
Copy the code

allEqualCheck that the array items are equal

allEqual(array)
Copy the code

parameter

  • arrayThe array to check

The sample

allEqual([1.2.3.4.5.6])
// => false

allEqual([1.1.1.1])
// => true
Copy the code

The source code

const allEqual = arr= > arr.every(val= > val === arr[0])
Copy the code

diffArrayIs the onlyarrayThe value of the array

Creates an array with unique array values that are not included in any other given array

diffArray(array, array2)
Copy the code

parameter

  • arrayThe array to check
  • array2The array to exclude

The sample

diffArray([1.2.6.7], [1.2.9.5])
// => [6, 7]
Copy the code

The source code

const diffArray = (a, b) = > {
    const s = new Set(b)
    let arr = a.filter(x= >! s.has(x))return arr
}
Copy the code

haveArrWith commonarrayThe value of the array

Creates an array with common array values, each contained in another given array

haveArr(array, array2)
Copy the code

parameter

  • arrayThe array to check
  • array2The array to include

The sample

haveArr([1.2.6.7], [1.2.9.5])
// => [1, 2]
Copy the code

The source code

const haveArr = (a, b) = > {
    const s = new Set(b)
    return a.filter(x= > s.has(x))
}
// ES6 includes
const haveArr = (arr, values) = > arr.filter(v= > values.includes(v))
Copy the code

uniqueArrayArray to heavy

Create a deduplicated array copy

uniqueArray(array)
Copy the code

parameter

  • arrayThe array to deduplicate

The sample

uniqueArray([1.2.2.3.4.4.5])
// => [1, 2, 3, 4, 5]
Copy the code

The source code

const uniqueArray = (. arr) = > [...new Set(arr)]

const uniqueArray = (. arr) = > Array.from(new Set(arr))
Copy the code

uniqueArrayObjectArray objects are deduplicated

Creates a stripped copy of array array objects

uniqueArrayObject(array)
Copy the code

parameter

  • arrayThe array to deduplicate
  • keyThe value of the object property to be repealed

The sample

const responseList = [
    { id: 1.a: 1 },
    { id: 2.a: 2 },
    { id: 3.a: 3 },
    { id: 1.a: 4 },
    { id: 2.a: 2 },
    { id: 3.a: 3 },
    { id: 1.a: 4 },
    { id: 2.a: 2 },
    { id: 3.a: 3 },
    { id: 1.a: 4 },
    { id: 2.a: 2 },
    { id: 3.a: 3 },
    { id: 1.a: 4 },
]

uniqueArrayObject(responseList, 'id')

// => [ { id: 1, a: 1 }, { id: 2, a: 2 }, { id: 3, a: 3 } ]
Copy the code

The source code

const uniqueArrayObject = (arr, key) = > {
    return arr.reduce((acc, cur) = > {
        const ids = acc.map(item= > item[key])
        return ids.includes(cur[key]) ? acc : [...acc, cur]
    }, [])
}
Copy the code

treeDataGenerate tree structured data

This function passes in an array, each id corresponding to its parent parent_id, and returns an array of tree structures

treeData(array, id, parent_id)
Copy the code

parameter

  • arrayAn array to generate a tree structure
  • idCustom attribute name
  • parent_idParent custom attribute name

The sample

const comments = [
    { id: 1.parent_id: null },
    { id: 2.parent_id: 1 },
    { id: 3.parent_id: 1 },
    { id: 4.parent_id: 2 },
    { id: 5.parent_id: 4 },
]

treeData(comments)

// => [ { id: 1, parent_id: null, children: [ [Object], [Object] ] } ]
Copy the code

The source code

const treeData = (arr, id = null, link = 'parent_id') = > arr.filter(item= > item[link] === id).map(item= > ({ ...item, children: treeData(arr, item.id) }))
Copy the code

ascArrAn array of ascending

Returns a new array in ascending order

The sort() method changes the array to unicode code order by default

ascArr(array)
Copy the code

parameter

  • arrayThe sorted array to check

The sample

ascArr([3.2.3.4.1])
// => [1, 2, 3, 3, 4]
Copy the code

The source code

// Via ES6... Expand operator to shallow copy a new array
const ascArr = arr= > [...arr].sort((a, b) = > a - b)
Copy the code

descArrAn array in descending order

Returns a new array in descending order

descArr(array)
Copy the code

parameter

  • arrayThe sorted array to check

The sample

descArr([3.2.3.4.1])
// => [1, 2, 3, 3, 4]
Copy the code

The source code

const descArr = arr= > [...arr].sort((a, b) = > b - a)
Copy the code

shuffleRandom sequence

Create a random array and use the Fisher-Yates algorithm to randomly sort the elements of the array

shuffle(array)
Copy the code

parameter

  • arrayI want random arrays

The sample

shuffle([2.3.1])
// => [3, 1, 2]
Copy the code

The source code

const shuffle = ([...arr]) = > {
    let m = arr.length
    while (m) {
        const i = Math.floor(Math.random() * m--) ; [arr[m], arr[i]] = [arr[i], arr[m]] }return arr
}
Copy the code

takeArrayIntercepts the element specified at the beginning of the array

Extract n elements from array starting with the first element of the array

takeArray(array, n)
Copy the code

parameter

  • arrayThe array to retrieve.
  • n=The element to extractnNumber.

The sample

takeArray([2.3.1].2)
/ / = > [2, 3]
Copy the code

The source code

const takeArray = (arr, n = 1) = > arr.slice(0, n)
Copy the code

takeLastArrayIntercepts the last element specified in the array

Extract n elements starting with the last element of array

takeLastArray(array, n)
Copy the code

parameter

  • arrayThe array to retrieve.
  • n=The element to extractnNumber.

The sample

takeArray([2.3.1].2)
/ / = > [3, 1)
Copy the code

The source code

const takeLastArray = (arr, n = 1) = > arr.slice(0, -n)
Copy the code

cloneArrayCloned array

Shallow copy a number of copies

cloneArray(array)
Copy the code

parameter

  • arrayThe array to copy

The sample

cloneArray([1.24])
/ / = > [24] 1,
Copy the code

The source code

// ES6 ...
const cloneArray = arr= > [...arr]

// ES6 Array.from
const cloneArray = arr= > Array.from(arr)

// concat()
const cloneArray = arr= > [].concat(arr)

// map()
const cloneArray = arr= > arr.map(x= > x)

cloneArray([1.24]) / / [24] 1,
Copy the code

maxArrayMaximum value in array

Filter all non-false elements in the original array and return the maximum value in the array

maxArray(array)
Copy the code

parameter

  • arrayAn array to be processed

The sample

maxArray([0, -1, -2, -3.false])
/ / = > 0
Copy the code

The source code

const maxArray = arr= > Math.max(... arr.filter(v= > Boolean(v) || v === 0))
Copy the code

minArrayThe smallest value in the array

Filter all non-false elements in the original array and return the minimum value in the array

minArray(array)
Copy the code

parameter

  • arrayAn array to be processed

The sample

minArray([0, -1, -2, -3.false])
/ / = > - 3
Copy the code

The source code

const minArray = arr= > Math.min(... arr.filter(v= > Boolean(v) || v === 0))
Copy the code

validArrayRemoves invalid values from arrays

Creates a new array containing all the non-false value elements in the original array. Examples of false, null,0, “”, undefined, and NaN are all considered “false values”.

validArray(array)
Copy the code

parameter

  • arrayAn array to be processed

The sample

minArray([0.1.false.2.' '.3])
// => [1, 2, 3]
Copy the code

The source code

const validArray = arr= > arr.filter(Boolean)
Copy the code

Second, the object

isObjectEqualCheck that the values of two objects are equal

isObjectEqual(object, object2)
Copy the code

parameter

  • objectThe object to retrieve
  • object2The object to retrieve

The sample

isObjectEqual({ a: 2.b: 4 }, { b: 4.a: 2 })
// => true
isObjectEqual({ a: 2.b: 4.c: 6 }, { b: 4.a: 2 })
// => false
Copy the code

The source code

function isObjectEqual(obj1, obj2, has = true) {
    // Determine the type
    const o1 = obj1 instanceof Object
    const o2 = obj2 instanceof Object
    if(! o1 || ! o2)return obj1 === obj2
    // Determine the length
    const keys1 = Object.getOwnPropertyNames(obj1)
    const keys2 = Object.getOwnPropertyNames(obj2)
    if(keys1.length ! == keys2.length)return false
    // Comparison of items
    for (let o in obj1) {
        let t1 = obj1[o] instanceof Object
        let t2 = obj2[o] instanceof Object
        if (t1 && t2) {
            has = diffByObj(obj1[o], obj2[o])
        } else if(obj1[o] ! == obj2[o]) { has =false
            break}}return has
}
Copy the code

cloneObjectClone object

Shallow copy a copy of an object

cloneObject(object)
Copy the code

parameter

  • objectThe object to copy

The sample

const a = { x: 1.y: 1 }
const b = cloneObject(a)
// => a ! == b
Copy the code

The source code

// ES6 ...
const cloneObject = (obj, temp = {}) = >(temp = { ... obj })// Object.assign()
const cloneObject = obj= > Object.assign({}, obj)
Copy the code

Three, functions,

debounceFunction image stabilization

The callback is executed n seconds after the event is triggered, and if it is triggered again within n seconds, the timer is reset.

debounce(fn, wait)
Copy the code

parameter

  • fnA function to prevent jitter
  • wait=500The number of milliseconds to delay

The sample

Debounce (()=> {console.log('debounce')}, 1000) // => print 'debounce' after 1 secondCopy the code

The source code

/** ** Anti-shake *@parmas Fn callback function *@parmas Time Specifies the time */
const debounce = (function () {
    let timer = {}
    return function (func, wait = 500) {
        let context = this // Note that this points to
        let args = arguments // arguments hold e
        let name = arguments[0].name || 'arrow' // Arrow function
        if (timer[name]) clearTimeout(timer[name])
        timer[name] = setTimeout(() = > {
            func.apply(this, args)
        }, wait)
    }
})()
Copy the code

throttleFunction of the throttle

Specify a unit of time. Within this unit of time, only one callback function that triggers an event can be executed. If an event is triggered multiple times within the same unit of time, only one callback function can take effect.

throttle(fn, wait)
Copy the code

parameter

  • fnThe function to be throttled
  • wait=500The number of milliseconds to delay

The sample

throttle(() = > {
    console.log('throttle')},1000)
// Trigger printing 'throttle' multiple times in 1 second
Copy the code

The source code

/** ** throttling (triggered at a specified time) *@parmas Fn completes the run callback *@parmas Delay Specifies the time */
export const throttle = (function () {
    let timeout = null
    return function (func, wait) {
        let context = this
        let args = arguments
        if(! timeout) { timeout =setTimeout(() = > {
                timeout = null
                func.apply(context, args)
            }, wait)
        }
    }
})()

throttle(fn, 300)
Copy the code

typeFnType judgment

Check whether the type is Array Object String Number

typeFn.type(value)
Copy the code

parameter

  • typeThe data type
  • valueThe value to be tested

The sample

typeFn.String('1')
typeFn.Number(1)
typeFn.Boolean(false)
typeFn.Null(null)
typeFn.Array([1.2])
typeFn.Object({ a: 1 })
typeFn.Function(() = > {})

// => true
Copy the code

The source code

let typeFn = {}
const curring = (fn, arr = []) = > {
    let len = fn.length
    return (. args) = > {
        arr = arr.concat(args)
        if (arr.length < len) {
            return curring(fn, arr)
        }
        returnfn(... arr) } }function isType(type, content) {
    return Object.prototype.toString.call(content) === `[object ${type}] `
}
;['String'.'Number'.'Boolean'.'Null'.'Array'.'Object'.'Function'].forEach(type= > {
    typeFn[type] = curring(isType)(type)
})
Copy the code

calcFnAddition, subtraction, multiplication and division

Because JavaScript follows the IEEE 754 math standard, it uses 64-bit floating-point numbers for operations. Precision is lost when decimal operations are performed.

calcFn.add(value1, value2, value3)
Copy the code

parameter

  • add,sub,mul,divThe operator
  • valueThe value to be computed

The sample

To solve0.1+0.2! = =0.3The problem/ / add
calcFn.add(0.1.0.2) / / 0.3

/ / subtraction
calcFn.sub(0.1.0.2) / / 0.1

/ / the multiplication
calcFn.mul(0.2.0.3) / / 0.06

/ / the multiplication
calcFn.add(0.1.0.2) / / 0.5
Copy the code

The source code

const calcFn = {
  add() {
      let arg = Array.from(arguments);
      return arg.reduce((total, num) = > {
          return accAdd(total, num);
      });
  },
  sub() {
      let arg = Array.from(arguments);
      return arg.reduce((total, num) = > {
          return accAdd(total, -num);
      });
  },
  mul() {
      let arg = Array.from(arguments);
      return arg.reduce((total, num) = > {
          return accMul(total, num);
      });
  },
  div() {
      let arg = Array.from(arguments);
      return arg.reduce((total, num) = > {
          returnaccDiv(total, num); }); }}function accAdd(arg1, arg2) {
  let r1, r2, m;
  try {
      r1 = arg1.toString().split(".") [1].length;
  } catch (e) {
      r1 = 0;
  }
  try {
      r2 = arg2.toString().split(".") [1].length;
  } catch (e) {
      r2 = 0;
  }
  m = Math.pow(10.Math.max(r1, r2));
  return (arg1 * m + arg2 * m) / m;
}

function accMul(arg1, arg2) {
  let m = 0,
      s1 = arg1.toString(),
      s2 = arg2.toString();
  try {
      m += s1.split(".") [1].length;
  } catch (e) {}
  try {
      m += s2.split(".") [1].length;
  } catch (e) {}
  return Number(s1.replace("."."")) * Number(s2.replace("."."")) / Math.pow(10, m);
}

function accDiv(arg1, arg2) {
  let t1 = 0,
      t2 = 0,
      r1, r2;
  try {
      t1 = arg1.toString().split(".") [1].length;
  } catch (e) {}
  try {
      t2 = arg2.toString().split(".") [1].length;
  } catch (e) {}
  r1 = Number(arg1.toString().replace(".".""));
  r2 = Number(arg2.toString().replace(".".""));
  return (r1 / r2) * Math.pow(10, t2 - t1);
}
Copy the code

4. String

isNilValues arenullorundefined

isNil(value)
Copy the code

parameter

  • valueThe value to be tested

The sample

isNil(null)
isNil(undefined)
// => true
Copy the code

The source code

const isNil = val= > val === undefined || val === null
Copy the code

padStartMasking string

padStart(value, n, maskChar)
Copy the code

parameter

  • valueTo cover up the string
  • n = 4Filling length
  • maskCharFill character

The sample

padStart('18659808664')
/ / = > 1865 * * * * * * *
Copy the code

The source code

const padStart = (str, n = 4, maskChar = The '*') = > str.slice(0, n).padStart(str.length, maskChar)
Copy the code

thousandsA semicolon is added to the number every three digits

thousands(number)
Copy the code

parameter

  • numberA number or floating point number

The sample

thousands(12255552323)
/ / = > 12255552 323
Copy the code

The source code

const thousands = num= > num.toString().replace(num.toString().indexOf('. ') > -1 ? /(\d)(? =(\d{3})+\.) /g : /(\d)(? =(\d{3})+$)/g.'$1')
Copy the code

Five, Numbers,

randomNumberSpecifies a range of random integers

randomNumber(min, max)
Copy the code

parameter

  • minSpecify a range minimum value
  • maxSpecify range maximum

The sample

randomNumber(0.10)
/ / = > 7
/ / = > 2
Copy the code

The source code

const randomNumber = (min = 0, max = 10) = > Math.floor(Math.random() * (max - min + 1)) + min
Copy the code

averageaveraging

average(value1, value2, value3)
Copy the code

parameter

  • valuedigital

The sample

average(... [1.2.3])
average(1.2.3)
/ / = > 2
Copy the code

The source code

const average = (. nums) = > nums.reduce((acc, val) = > acc + val, 0) / nums.length
Copy the code

averageByCheck the equality of the items in the array object

averageBy(array, fn)
Copy the code

parameter

  • arrayThe array to iterate over
  • fnIterative function

The sample

averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6}].o= > o.n)
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6}].'n')
/ / = > 5
Copy the code

The source code

const averageBy = (arr, fn) = > arr.map(typeof fn === 'function' ? fn : val= > val[fn]).reduce((acc, val) = > acc + val, 0) / arr.length
Copy the code

aboutEqualAre these two values approximately equal to

If two numbers are passed in roughly equal, the error is within acceptable limits

aboutEqual(n1, n2, epsilon)
Copy the code

parameter

  • n1 n2The number to compare
  • epsilonAcceptable error range

The sample

aboutEqual(25.2.0.06)
// => true
Copy the code

The source code

const aboutEqual = (n1, n2, epsilon = 0.001) = > Math.abs(n1 - n2) < epsilon
Copy the code

getLineSizeCalculate the distance between two points

The Pythagorean theorem computes the distance between two points

getLineSize = (x1, y1, x2, y2)
Copy the code

parameter

  • x1 y1 x2 y2The coordinate points

The sample

getLineSize(0.0.3.4)
/ / = > 5
Copy the code

The source code

const getLineSize = (x1, y1, x2, y2) = > Math.hypot(x2 - x1, y2 - y1)
Copy the code

sumThe sum of values in an array

sum(value1, value2, value3)
Copy the code

parameter

  • value1 value2 value3The number to iterate over

The sample

sum(1.2.3.4) sum(... [1.2.3.4])
/ / = > 10
Copy the code

The source code

const sum = (. arr) = > [...arr].reduce((acc, val) = > acc + val, 0)
Copy the code

Vi. Browser

copyTextH5 Copies the text

copyText(content, callback)
Copy the code

parameter

  • contentTo copy text
  • callbackCallback user prompt

The sample

copyText(content, text= > {
    this.$toast(text)
})
Copy the code

The source code

function copyText(content, callback) {
    if (!document.queryCommandSupported('copy')) {
        // To be compatible with some browsers queryCommandSupported judgments
        console.log('Browser not supported')
        return
    }
    let textarea = document.createElement('textarea')
    textarea.value = content
    textarea.readOnly = 'readOnly'
    document.body.appendChild(textarea)
    textarea.select() // Select the object
    textarea.setSelectionRange(0, content.length) / / core
    let result = document.execCommand('copy') // Execute the browser copy command
    callback && callback(result ? 'Copy succeeded ~~' : 'Replication failed ~~')
    textarea.remove()
}
Copy the code

getCurrentURLGets the current URL address

This function returns the URL of the current page.

The sample

getCurrentURL()
/ / = >
Copy the code

The source code

const getCurrentURL = () = > window.location.href
Copy the code

scrollToTopReturn to the top

Scroll smoothly to the top of the current page.

The sample

scrollToTop()
// => Top of the current page
Copy the code

The source code

const scrollToTop = () = > {
    const c = document.documentElement.scrollTop || document.body.scrollTop
    if (c > 0) {
        window.requestAnimationFrame(scrollToTop)
        window.scrollTo(0, c - c / 8)}}Copy the code

smoothScrollSmooth scrolling page

Scroll smoothly to the visible area of the browser window

The sample

smoothScroll('#fooBar');
// => Scroll smoothly to the element with ID fooBarSmoothScroll ('.fooBar');// => Use the fooBar class to scroll smoothly to the first element
Copy the code

The source code

const smoothScroll = element= >
    document.querySelector(element).scrollIntoView({
        behavior: 'smooth',})Copy the code

5.isCurrentPageIs the current page

The browser TAB is whether the user is browsing

The sample

isCurrentPage()
// => true
Copy the code

The source code

isCurrentPage = () = > !document.hidden
Copy the code

Environment of 7.

1.isBrowserBrowser or not

Returns whether the current runtime environment is a browser

The sample

isBrowser()
// => true (browser)
// => false (Node)
Copy the code

The source code

const isBrowser = () = >! [typeof window.typeof document].includes('undefined')
Copy the code

2.isWechatBrowserJudge wechat browser or ordinary H5

The sample

isWechatBrowser()
// => true
Copy the code

The source code

const isWechatBrowser = (() = > {
    let ua = navigator.userAgent.toLowerCase()
    return /micromessenger/.test(ua)
})()
Copy the code

3.isMobileCheck whether it is a mobile terminal

The sample

isMobile()
// => true
Copy the code

The source code

const isMobile = () = > /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
Copy the code

The resources

  • 30 seconds of code
  • lodash