Implementation of common front-end functions

0: Get the address bar parameters getUrlParams

function getUrlParam(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
      var r = window.location.search.substr(1).match(reg);  //匹配目标参数
      if (r != null) return unescape(r[2]); return null; //返回参数值
 } 

 

1: Create a traversable array of specified length

var a = Array.apply( null, { length: 3 } );  //  [ undefined, undefined, undefined ]

var c = Array.from( { length: 4 } );  // 新增api
 

2: Get the original link of the iframe in the window of the iframe (the iframe layout of the middle-station management system)

window.frameElement.getAttribute('src')

3: Determine the type of any value

// return 'array', 'object', 'function', 'null', 'undefined', 'string', 'number'
export const typeOf = input => {
  return ({}).toString.call(input).slice(8, -1).toLowerCase();
};

4: Array filter weight

//简单数组
var arr=[1,2,1,'1',null,null,undefined,undefined,NaN,NaN]
let res=Array.from(new Set(arr));//{1,2,"1",null,undefined,NaN}
//or
let newarr=[...new Set(arr)]

// 数组对象


let person = [
     {id: 0, name: "小明"},
     {id: 1, name: "小张"},
     {id: 2, name: "小李"},
     {id: 3, name: "小孙"},
     {id: 1, name: "小周"},
     {id: 2, name: "小陈"},  
];
 
let obj = {};
 
let peon = person.reduce((cur,next) => {
    obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
    return cur;
},[]) //设置cur默认类型为数组,并且初始值为空的数组
console.log(peon);

5: The method of converting the actual parameters of the function into an array

方法一:var args = Array.prototype.slice.call(arguments);

方法二:var args = [].slice.call(arguments, 0);

6: Check that a number is an integer

x === Math.floor( x );

或者

Number.isInteger( 4 ); // 新增api

7: Judging the type

JavaScript is not a strongly typed language, and the best solution I recommend is TypeScript. But sometimes you just want a simple type check, in this case JavaScript allows you to use the "typeof" keyword.

The problem with "typeof" is that it works well when used with certain primitives and functions, but for arrays and objects, since they are both regarded as "objects", it is difficult to grasp the difference between them.

const isOfType = (() => {
  // create a plain object with no prototype
  const type = Object.create(null);

  // check for null type
  type.null = x => x === null;
  // check for undefined type
  type.undefined = x => x === undefined;
  // check for nil type. Either null or undefined
  type.nil = x => type.null(x) || type.undefined(x);
  // check for strings and string literal type. e.g: 's', "s", `str`, new String()
  type.string = x => !type.nil(x) && (typeof x === 'string' || x instanceof String);
  // check for number or number literal type. e.g: 12, 30.5, new Number()
  type.number = x => !type.nil(x) 
    && (// NaN & Infinity have typeof "number" and this excludes that
      (!isNaN(x) && isFinite(x)
      && typeof x === 'number'
    ) || x instanceof Number);
  // check for boolean or boolean literal type. e.g: true, false, new Boolean()
  type.boolean = x => !type.nil(x) && (typeof x === 'boolean' || x instanceof Boolean);
  // check for array type
  type.array = x => !type.nil(x) && Array.isArray(x);
  // check for object or object literal type. e.g: {}, new Object(), Object.create(null)
  type.object = x => ({}).toString.call(x) === '[object Object]';
  // check for provided type instance
  type.type = (x, X) => !type.nil(x) && x instanceof X;
  // check for set type
  type.set = x => type.type(x, Set);
  // check for map type
  type.map = x => type.type(x, Map);
  // check for date type
  type.date = x => type.type(x, Date);

  return type;
})();

8: Determine the null value

Sometimes you need to know whether some content is empty and decide which method to use based on the result, such as checking the length, size, or whether it contains any sub-elements. The following tool packs these functions, you can use it to check the size of String, Object, Array, Map and Set.

function isEmpty(x) {
  if(Array.isArray(x)
    || typeof x === 'string'
    || x instanceof String
   ) {
    return x.length === 0;
  }

  if(x instanceof Map || x instanceof Set) {
    return x.size === 0;
  }

  if(({}).toString.call(x) === '[object Object]') {
    return Object.keys(x).length === 0;
  }

  return false;
}

9: Random number generator

function randomNumber(max = 1, min = 0) {
  if(min >= max) {
    return max;
  }

  return Math.floor(Math.random() * (max - min) + min);
}

10: Deep clone object

const deepClone = obj => {
  let clone = obj;
  if (obj && typeof obj === "object") {
    clone = new obj.constructor();

    Object.getOwnPropertyNames(obj).forEach(
      prop => (clone[prop] = deepClone(obj[prop]))
    );
  }
  return clone;
};

 

Guess you like

Origin blog.csdn.net/lianjiuxiao/article/details/110532934
Recommended