step by step教你常用JS方法封装(一) [ 大杂烩 ]

本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6338/

持续更新中...

常用JS方法封装方法预告:

  • 项目常用JS方法封装(二) [ 时间处理 ]
  • 项目常用JS方法封装(三) [ 字符串相关处理 ]
  • 项目常用JS方法封装(四) [ 数组相关处理 ]


使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!

001.输入一个值,返回其数据类型

type = para => {
  return Object.prototype.toString.call(para).slice(8,-1)
}
复制代码

002.阶乘

factorial = num => {
  let count = 1;
  for (let i = 1; i <= num; i++) {
    count *= i;
  }
  return count;
}
复制代码

003.两个数之间累乘

multBetride = (x, y) => {
  let count;
  if (x < y) {
    count = x;
    for (let i = x + 1; i <= y; i++) {
      count *= i;
    }
    return count;
  } else {
    count = y;
    for (let i = y + 1; i <= x; i++) {
      count *= i;
    }
    return count;
  }
}
复制代码

004.累加

()里面可以放N个实参

function cumsum() {
    let sum = 0;
    for (let i = 0; i < arguments.length; i++) {
        sum += arguments[i];
    }
    return sum;
}
复制代码

005.计时器(计算代码块(函数)执行时间)

无参 computeTime(f)

computeTime = code => {
  let startTime = new Date().getTime();
  code();
  let endTime = new Date().getTime();
  let time = endTime - startTime;
  return time;
}
复制代码

有参 computeTime(f) 使用方法:computeTime(f,参数1,参数2......)

computeTime = f => {
  let startTime = new Date().getTime();
  let p = [];
  for (let i = 1; i < arguments.length; i++) {
    p.push(arguments[i])
  }
  f.apply(null, p)
  let endTime = new Date().getTime();
  let Time = endTime - startTime;
  return Time;
}
复制代码

006.数字超过9显示省略号

num_filter = val =>{
  val = val?val-0:0;
  if (val > 9 ) {
    return "…"
  }else{
    return val;
  }
}
复制代码

007.数字超过99显示99+

ninenum_filter = val =>{
  val = val?val-0:0;
  if (val > 99 ) {
    return "99+"
  }else{
    return val;
  }
}
复制代码

008.银行卡号分割

bank_filter = val =>{
  val += ‘‘;
  val = val.replace(/(\s)/g,‘‘).replace(/(\d{4})/g,‘$1 ‘).replace(/\s*$/,‘‘);
  return val;
}
复制代码

009.防抖与节流

/**
 * 函数防抖 (只执行最后一次点击)
 */
Debounce = (fn, t) => {
    let delay = t || 500;
    let timer;
    return function () {
        let args = arguments;
        if(timer){
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            timer = null;
            fn.apply(this, args);
        }, delay);
    }
};
/*
 * 函数节流
 */
Throttle = (fn, t) => {
    let last;
    let timer;
    let interval = t || 500;
    return function () {
        let args = arguments;
        let now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                last = now;
                fn.apply(this, args);
            }, interval);
        } else {
            last = now;
            fn.apply(this, args);
        }
    }
};  

复制代码

010.深拷贝

deepClone = source => {
  const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象
  for (let keys in source) { // 遍历目标
    if (source.hasOwnProperty(keys)) {
      if (source[keys] && typeof source[keys] === ‘object‘) { // 如果值是对象,就递归一下
        targetObj[keys] = source[keys].constructor === Array ? [] : {};
        targetObj[keys] = deepClone(source[keys]);
      } else { // 如果不是,就直接赋值
        targetObj[keys] = source[keys];
      }
    }
  }
  return targetObj;
}  

let str1 = {
  arr: [1, 2, 3],
  obj: {
    key: ‘value‘
  },
  fn: function () {
    return 1;
  }
};
let str3 = deepClone(str1);  

console.log(str3 === str1); // false
console.log(str3.obj === str1.obj); // false
console.log(str3.fn === str1.fn); // true
复制代码

011.获取视口尺寸

需要在HTML文件中运行

function getViewportOffset() {
    if (window.innerWidth) {
        return {
            w: window.innerWidth,
            h: window.innerHeight
        }
    } else {
        // ie8及其以下
        if (document.compatMode === "BackCompat") {
            // 怪异模式
            return {
                w: document.body.clientWidth,
                h: document.body.clientHeight
            }
        } else {
            // 标准模式
            return {
                w: document.documentElement.clientWidth,
                h: document.documentElement.clientHeight
            }
        }
    }
}
复制代码

012.数字前补零

/**
*   num为你想要进行填充的数字
*   length为你想要的数字长度
*/  

//迭代方式实现
padding1=(num, length)=> {
  for(let len = (num + "").length; len < length; len = num.length) {
      num = "0" + num;
  }
  return num;
}  

//递归方式实现
padding2=(num, length) =>{
  if((num + "").length >= length) {
      return num;
  }
  return padding2("0" + num, length)
}  

//转为小数
padding3=(num, length)=> {
  let decimal = num / Math.pow(10, length);
  //toFixed指定保留几位小数
  decimal = decimal.toFixed(length) + "";
  return decimal.substr(decimal.indexOf(".")+1);
}  

//填充截取法
padding4=(num, length)=> {
  //这里用slice和substr均可
  return (Array(length).join("0") + num).slice(-length);
}  

//填充截取法
padding5=(num, length)=> {
  let len = (num + "").length;
  let diff = length+1 - len;
  if(diff > 0) {
      return Array(diff).join("0") + num;
  }
  return num;
}
复制代码

013.格式转换:base64转file

/**
*   base64 base64
*   filename 转换后的文件名
*/
base64ToFile = (base64, filename )=> {
  let arr = base64.split(‘,‘)
  let mime = arr[0].match(/难过.*?);/)[1]
  let suffix = mime.split(‘/‘)[1] // 图片后缀
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], `${filename}.${suffix}`, { type: mime })
}
复制代码

014.格式转换:base64转blob

base64ToBlob = base64 => {
  let arr = base64.split(‘,‘),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
};
复制代码

015.格式转换:blob转file

blobToFile = (blob, fileName) => {
  blob.lastModifiedDate = new Date();
  blob.name = fileName;
  return blob;
};
复制代码

016.格式转换:file转base64

/**
 * file 图片文件
 * 返回图片的Base64数据
 */
fileToBase64 = file => {
  let reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = function (e) {
    return e.target.result
  };
}
复制代码

017.获取地址栏传递过来的参数

/**
 * name为地址栏传递过来的字段名
 */
getQueryString = name => {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  let r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]); return null;
}  

//  测试
// http://localhost:3306/admin?id=111&name=xxx
// console.log(getQueryString(‘id‘));  // 111
// console.log(getQueryString(‘name‘));  // xxx
复制代码

018.对象处理为数组对象

/**
 *  obj 需要处理的对象
 */
objToArrObj = obj => {
  let arr = []
  for(let i in obj){
    arr.push({[i]:obj[i]})
  }
  return arr
}  

//  测试数据
let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}
console.log(objToArrObj(obj));
/*
  [
    { 20180410: 5 },
    { 20180411: 13 },
    { 20180412: 26 },
    { 20180413: 16 }
  ]
*/
```本文参考原文-http://bjbsair.com/2020-03-25/tech-info/6338/

![手把手教你常用JS方法封装(一) [ 大杂烩 ]](http://p3.pstatp.com/large/dfic-imagehandler/a3548031-8354-4d74-a3c5-dd39f97e2390)

持续更新中...
========

常用JS方法封装方法预告:

*   项目常用JS方法封装(二) [ 时间处理 ]
*   项目常用JS方法封装(三) [ 字符串相关处理 ]
*   项目常用JS方法封装(四) [ 数组相关处理 ]

* * *

**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**

001.输入一个值,返回其数据类型
=================

type = para => {

return Object.prototype.toString.call(para).slice(8,-1)

}

复制代码


002.阶乘
======

factorial = num => {

let count = 1;

for (let i = 1; i <= num; i++) {

count *= i;

}

return count;

}

复制代码


003.两个数之间累乘
===========

multBetride = (x, y) => {

let count;

if (x < y) {

count = x;

for (let i = x + 1; i <= y; i++) {

count *= i;

}

return count;

} else {

count = y;

for (let i = y + 1; i <= x; i++) {

count *= i;

}

return count;

}

}

复制代码


004.累加
======

()里面可以放N个实参

function cumsum() {

let sum = 0;

for (let i = 0; i < arguments.length; i++) {

sum += arguments[i];

}

return sum;

}

复制代码


005.计时器(计算代码块(函数)执行时间)
======================

**无参 computeTime(f)**

computeTime = code => {

let startTime = new Date().getTime();

code();

let endTime = new Date().getTime();

let time = endTime - startTime;

return time;

}

复制代码


**有参 computeTime(f)** 使用方法:computeTime(f,参数1,参数2......)

computeTime = f => {

let startTime = new Date().getTime();

let p = [];

for (let i = 1; i < arguments.length; i++) {

p.push(arguments[i])

}

f.apply(null, p)

let endTime = new Date().getTime();

let Time = endTime - startTime;

return Time;

}

复制代码


006.数字超过9显示省略号
==============

num_filter = val =>{

val = val?val-0:0;

if (val > 9 ) {

return "…"

}else{

return val;

}

}

复制代码


007.数字超过99显示99+
===============

ninenum_filter = val =>{

val = val?val-0:0;

if (val > 99 ) {

return "99+"

}else{

return val;

}

}

复制代码


008.银行卡号分割
==========

bank_filter = val =>{

val += ‘‘;

val = val.replace(/(\s)/g,‘‘).replace(/(\d{4})/g,‘$1 ‘).replace(/\s*$/,‘‘);

return val;

}

复制代码


009.防抖与节流
=========

/**

  • 函数防抖 (只执行最后一次点击)

    /

    Debounce = (fn, t) => {

    let delay = t || 500;

    let timer;

    return function () {

    let args = arguments;

    if(timer){

    clearTimeout(timer);

    }

    timer = setTimeout(() => {

    timer = null;

    fn.apply(this, args);

    }, delay);

    }

    };

    /

  • 函数节流

    */

    Throttle = (fn, t) => {

    let last;

    let timer;

    let interval = t || 500;

    return function () {

    let args = arguments;

    let now = +new Date();

    if (last && now - last < interval) {

    clearTimeout(timer);

    timer = setTimeout(() => {

    last = now;

    fn.apply(this, args);

    }, interval);

    } else {

    last = now;

    fn.apply(this, args);

    }

    }

    };

复制代码


010.深拷贝
=======

deepClone = source => {

const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象

for (let keys in source) { // 遍历目标

if (source.hasOwnProperty(keys)) {

if (source[keys] && typeof source[keys] === ‘object‘) { // 如果值是对象,就递归一下

targetObj[keys] = source[keys].constructor === Array ? [] : {};

targetObj[keys] = deepClone(source[keys]);

} else { // 如果不是,就直接赋值

targetObj[keys] = source[keys];

}

}

}

return targetObj;

}

let str1 = {

arr: [1, 2, 3],

obj: {

key: ‘value‘

},

fn: function () {

return 1;

}

};

let str3 = deepClone(str1);

console.log(str3 === str1); // false

console.log(str3.obj === str1.obj); // false

console.log(str3.fn === str1.fn); // true

复制代码


011.获取视口尺寸
==========

**需要在HTML文件中运行**

function getViewportOffset() {

if (window.innerWidth) {

return {

w: window.innerWidth,

h: window.innerHeight

}

} else {

// ie8及其以下

if (document.compatMode === "BackCompat") {

// 怪异模式

return {

w: document.body.clientWidth,

h: document.body.clientHeight

}

} else {

// 标准模式

return {

w: document.documentElement.clientWidth,

h: document.documentElement.clientHeight

}

}

}

}

复制代码


012.数字前补零
=========

/**

  • num为你想要进行填充的数字
  • length为你想要的数字长度

    */

//迭代方式实现

padding1=(num, length)=> {

for(let len = (num + "").length; len < length; len = num.length) {

num = "0" + num;

}

return num;

}

//递归方式实现

padding2=(num, length) =>{

if((num + "").length >= length) {

return num;

}

return padding2("0" + num, length)

}

//转为小数

padding3=(num, length)=> {

let decimal = num / Math.pow(10, length);

//toFixed指定保留几位小数

decimal = decimal.toFixed(length) + "";

return decimal.substr(decimal.indexOf(".")+1);

}

//填充截取法

padding4=(num, length)=> {

//这里用slice和substr均可

return (Array(length).join("0") + num).slice(-length);

}

//填充截取法

padding5=(num, length)=> {

let len = (num + "").length;

let diff = length+1 - len;

if(diff > 0) {

return Array(diff).join("0") + num;

}

return num;

}

复制代码


013.格式转换:base64转file
====================

/**

  • base64 base64
  • filename 转换后的文件名

    /

    base64ToFile = (base64, filename )=> {

    let arr = base64.split(‘,‘)

    let mime = arr[0].match(/难过.?);/)[1]

    let suffix = mime.split(‘/‘)[1] // 图片后缀

    let bstr = atob(arr[1])

    let n = bstr.length

    let u8arr = new Uint8Array(n)

    while (n--) {

    u8arr[n] = bstr.charCodeAt(n)

    }

    return new File([u8arr], ${filename}.${suffix}, { type: mime })

    }

    复制代码


014.格式转换:base64转blob
====================

base64ToBlob = base64 => {

let arr = base64.split(‘,‘),

mime = arr[0].match(/??.*?);/)[1],

bstr = atob(arr[1]),

n = bstr.length,

u8arr = new Uint8Array(n);

while (n--) {

u8arr[n] = bstr.charCodeAt(n);

}

return new Blob([u8arr], { type: mime });

};

复制代码


015.格式转换:blob转file
==================

blobToFile = (blob, fileName) => {

blob.lastModifiedDate = new Date();

blob.name = fileName;

return blob;

};

复制代码


016.格式转换:file转base64
====================

/**

  • file 图片文件
  • 返回图片的Base64数据

    */

    fileToBase64 = file => {

    let reader = new FileReader();

    reader.readAsDataURL(file);

    reader.onload = function (e) {

    return e.target.result

    };

    }

    复制代码


017.获取地址栏传递过来的参数
================

/**

  • name为地址栏传递过来的字段名

    /

    getQueryString = name => {

    let reg = new RegExp("(^|&)" + name + "=([^&])(&|$)");

    let r = window.location.search.substr(1).match(reg);

    if (r != null) return unescape(r[2]); return null;

    }

// 测试

// http://localhost:3306/admin?id=111&name=xxx

// console.log(getQueryString(‘id‘)); // 111

// console.log(getQueryString(‘name‘)); // xxx

复制代码


018.对象处理为数组对象
=============

/**

  • obj 需要处理的对象

    */

    objToArrObj = obj => {

    let arr = []

    for(let i in obj){

    arr.push({[i]:obj[i]})

    }

    return arr

    }

// 测试数据

let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}

console.log(objToArrObj(obj));

/*

[

{ 20180410: 5 },

{ 20180411: 13 },

{ 20180412: 26 },

{ 20180413: 16 }

]

*/

  

![手把手教你常用JS方法封装(一) [ 大杂烩 ]](http://p3.pstatp.com/large/dfic-imagehandler/a3548031-8354-4d74-a3c5-dd39f97e2390)

持续更新中...
========

常用JS方法封装方法预告:

*   项目常用JS方法封装(二) [ 时间处理 ]
*   项目常用JS方法封装(三) [ 字符串相关处理 ]
*   项目常用JS方法封装(四) [ 数组相关处理 ]

* * *

**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**

001.输入一个值,返回其数据类型
=================

type = para => {

return Object.prototype.toString.call(para).slice(8,-1)

}

复制代码


002.阶乘
======

factorial = num => {

let count = 1;

for (let i = 1; i <= num; i++) {

count *= i;

}

return count;

}

复制代码


003.两个数之间累乘
===========

multBetride = (x, y) => {

let count;

if (x < y) {

count = x;

for (let i = x + 1; i <= y; i++) {

count *= i;

}

return count;

} else {

count = y;

for (let i = y + 1; i <= x; i++) {

count *= i;

}

return count;

}

}

复制代码


004.累加
======

()里面可以放N个实参

function cumsum() {

let sum = 0;

for (let i = 0; i < arguments.length; i++) {

sum += arguments[i];

}

return sum;

}

复制代码


005.计时器(计算代码块(函数)执行时间)
======================

**无参 computeTime(f)**

computeTime = code => {

let startTime = new Date().getTime();

code();

let endTime = new Date().getTime();

let time = endTime - startTime;

return time;

}

复制代码


**有参 computeTime(f)** 使用方法:computeTime(f,参数1,参数2......)

computeTime = f => {

let startTime = new Date().getTime();

let p = [];

for (let i = 1; i < arguments.length; i++) {

p.push(arguments[i])

}

f.apply(null, p)

let endTime = new Date().getTime();

let Time = endTime - startTime;

return Time;

}

复制代码


006.数字超过9显示省略号
==============

num_filter = val =>{

val = val?val-0:0;

if (val > 9 ) {

return "…"

}else{

return val;

}

}

复制代码


007.数字超过99显示99+
===============

ninenum_filter = val =>{

val = val?val-0:0;

if (val > 99 ) {

return "99+"

}else{

return val;

}

}

复制代码


008.银行卡号分割
==========

bank_filter = val =>{

val += ‘‘;

val = val.replace(/(\s)/g,‘‘).replace(/(\d{4})/g,‘$1 ‘).replace(/\s*$/,‘‘);

return val;

}

复制代码


009.防抖与节流
=========

/**

  • 函数防抖 (只执行最后一次点击)

    /

    Debounce = (fn, t) => {

    let delay = t || 500;

    let timer;

    return function () {

    let args = arguments;

    if(timer){

    clearTimeout(timer);

    }

    timer = setTimeout(() => {

    timer = null;

    fn.apply(this, args);

    }, delay);

    }

    };

    /

  • 函数节流

    */

    Throttle = (fn, t) => {

    let last;

    let timer;

    let interval = t || 500;

    return function () {

    let args = arguments;

    let now = +new Date();

    if (last && now - last < interval) {

    clearTimeout(timer);

    timer = setTimeout(() => {

    last = now;

    fn.apply(this, args);

    }, interval);

    } else {

    last = now;

    fn.apply(this, args);

    }

    }

    };

复制代码


010.深拷贝
=======

deepClone = source => {

const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象

for (let keys in source) { // 遍历目标

if (source.hasOwnProperty(keys)) {

if (source[keys] && typeof source[keys] === ‘object‘) { // 如果值是对象,就递归一下

targetObj[keys] = source[keys].constructor === Array ? [] : {};

targetObj[keys] = deepClone(source[keys]);

} else { // 如果不是,就直接赋值

targetObj[keys] = source[keys];

}

}

}

return targetObj;

}

let str1 = {

arr: [1, 2, 3],

obj: {

key: ‘value‘

},

fn: function () {

return 1;

}

};

let str3 = deepClone(str1);

console.log(str3 === str1); // false

console.log(str3.obj === str1.obj); // false

console.log(str3.fn === str1.fn); // true

复制代码


011.获取视口尺寸
==========

**需要在HTML文件中运行**

function getViewportOffset() {

if (window.innerWidth) {

return {

w: window.innerWidth,

h: window.innerHeight

}

} else {

// ie8及其以下

if (document.compatMode === "BackCompat") {

// 怪异模式

return {

w: document.body.clientWidth,

h: document.body.clientHeight

}

} else {

// 标准模式

return {

w: document.documentElement.clientWidth,

h: document.documentElement.clientHeight

}

}

}

}

复制代码


012.数字前补零
=========

/**

  • num为你想要进行填充的数字
  • length为你想要的数字长度

    */

//迭代方式实现

padding1=(num, length)=> {

for(let len = (num + "").length; len < length; len = num.length) {

num = "0" + num;

}

return num;

}

//递归方式实现

padding2=(num, length) =>{

if((num + "").length >= length) {

return num;

}

return padding2("0" + num, length)

}

//转为小数

padding3=(num, length)=> {

let decimal = num / Math.pow(10, length);

//toFixed指定保留几位小数

decimal = decimal.toFixed(length) + "";

return decimal.substr(decimal.indexOf(".")+1);

}

//填充截取法

padding4=(num, length)=> {

//这里用slice和substr均可

return (Array(length).join("0") + num).slice(-length);

}

//填充截取法

padding5=(num, length)=> {

let len = (num + "").length;

let diff = length+1 - len;

if(diff > 0) {

return Array(diff).join("0") + num;

}

return num;

}

复制代码


013.格式转换:base64转file
====================

/**

  • base64 base64
  • filename 转换后的文件名

    /

    base64ToFile = (base64, filename )=> {

    let arr = base64.split(‘,‘)

    let mime = arr[0].match(/难过.?);/)[1]

    let suffix = mime.split(‘/‘)[1] // 图片后缀

    let bstr = atob(arr[1])

    let n = bstr.length

    let u8arr = new Uint8Array(n)

    while (n--) {

    u8arr[n] = bstr.charCodeAt(n)

    }

    return new File([u8arr], ${filename}.${suffix}, { type: mime })

    }

    复制代码


014.格式转换:base64转blob
====================

base64ToBlob = base64 => {

let arr = base64.split(‘,‘),

mime = arr[0].match(/??.*?);/)[1],

bstr = atob(arr[1]),

n = bstr.length,

u8arr = new Uint8Array(n);

while (n--) {

u8arr[n] = bstr.charCodeAt(n);

}

return new Blob([u8arr], { type: mime });

};

复制代码


015.格式转换:blob转file
==================

blobToFile = (blob, fileName) => {

blob.lastModifiedDate = new Date();

blob.name = fileName;

return blob;

};

复制代码


016.格式转换:file转base64
====================

/**

  • file 图片文件
  • 返回图片的Base64数据

    */

    fileToBase64 = file => {

    let reader = new FileReader();

    reader.readAsDataURL(file);

    reader.onload = function (e) {

    return e.target.result

    };

    }

    复制代码


017.获取地址栏传递过来的参数
================

/**

  • name为地址栏传递过来的字段名

    /

    getQueryString = name => {

    let reg = new RegExp("(^|&)" + name + "=([^&])(&|$)");

    let r = window.location.search.substr(1).match(reg);

    if (r != null) return unescape(r[2]); return null;

    }

// 测试

// http://localhost:3306/admin?id=111&name=xxx

// console.log(getQueryString(‘id‘)); // 111

// console.log(getQueryString(‘name‘)); // xxx

复制代码


018.对象处理为数组对象
=============

/**

  • obj 需要处理的对象

    */

    objToArrObj = obj => {

    let arr = []

    for(let i in obj){

    arr.push({[i]:obj[i]})

    }

    return arr

    }

// 测试数据

let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}

console.log(objToArrObj(obj));

/*

[

{ 20180410: 5 },

{ 20180411: 13 },

{ 20180412: 26 },

{ 20180413: 16 }

]

*/

  

![手把手教你常用JS方法封装(一) [ 大杂烩 ]](http://p3.pstatp.com/large/dfic-imagehandler/a3548031-8354-4d74-a3c5-dd39f97e2390)

持续更新中...
========

常用JS方法封装方法预告:

*   项目常用JS方法封装(二) [ 时间处理 ]
*   项目常用JS方法封装(三) [ 字符串相关处理 ]
*   项目常用JS方法封装(四) [ 数组相关处理 ]

* * *

**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**

001.输入一个值,返回其数据类型
=================

type = para => {

return Object.prototype.toString.call(para).slice(8,-1)

}

复制代码


002.阶乘
======

factorial = num => {

let count = 1;

for (let i = 1; i <= num; i++) {

count *= i;

}

return count;

}

复制代码


003.两个数之间累乘
===========

multBetride = (x, y) => {

let count;

if (x < y) {

count = x;

for (let i = x + 1; i <= y; i++) {

count *= i;

}

return count;

} else {

count = y;

for (let i = y + 1; i <= x; i++) {

count *= i;

}

return count;

}

}

复制代码


004.累加
======

()里面可以放N个实参

function cumsum() {

let sum = 0;

for (let i = 0; i < arguments.length; i++) {

sum += arguments[i];

}

return sum;

}

复制代码


005.计时器(计算代码块(函数)执行时间)
======================

**无参 computeTime(f)**

computeTime = code => {

let startTime = new Date().getTime();

code();

let endTime = new Date().getTime();

let time = endTime - startTime;

return time;

}

复制代码


**有参 computeTime(f)** 使用方法:computeTime(f,参数1,参数2......)

computeTime = f => {

let startTime = new Date().getTime();

let p = [];

for (let i = 1; i < arguments.length; i++) {

p.push(arguments[i])

}

f.apply(null, p)

let endTime = new Date().getTime();

let Time = endTime - startTime;

return Time;

}

复制代码


006.数字超过9显示省略号
==============

num_filter = val =>{

val = val?val-0:0;

if (val > 9 ) {

return "…"

}else{

return val;

}

}

复制代码


007.数字超过99显示99+
===============

ninenum_filter = val =>{

val = val?val-0:0;

if (val > 99 ) {

return "99+"

}else{

return val;

}

}

复制代码


008.银行卡号分割
==========

bank_filter = val =>{

val += ‘‘;

val = val.replace(/(\s)/g,‘‘).replace(/(\d{4})/g,‘$1 ‘).replace(/\s*$/,‘‘);

return val;

}

复制代码


009.防抖与节流
=========

/**

  • 函数防抖 (只执行最后一次点击)

    /

    Debounce = (fn, t) => {

    let delay = t || 500;

    let timer;

    return function () {

    let args = arguments;

    if(timer){

    clearTimeout(timer);

    }

    timer = setTimeout(() => {

    timer = null;

    fn.apply(this, args);

    }, delay);

    }

    };

    /

  • 函数节流

    */

    Throttle = (fn, t) => {

    let last;

    let timer;

    let interval = t || 500;

    return function () {

    let args = arguments;

    let now = +new Date();

    if (last && now - last < interval) {

    clearTimeout(timer);

    timer = setTimeout(() => {

    last = now;

    fn.apply(this, args);

    }, interval);

    } else {

    last = now;

    fn.apply(this, args);

    }

    }

    };

复制代码


010.深拷贝
=======

deepClone = source => {

const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象

for (let keys in source) { // 遍历目标

if (source.hasOwnProperty(keys)) {

if (source[keys] && typeof source[keys] === ‘object‘) { // 如果值是对象,就递归一下

targetObj[keys] = source[keys].constructor === Array ? [] : {};

targetObj[keys] = deepClone(source[keys]);

} else { // 如果不是,就直接赋值

targetObj[keys] = source[keys];

}

}

}

return targetObj;

}

let str1 = {

arr: [1, 2, 3],

obj: {

key: ‘value‘

},

fn: function () {

return 1;

}

};

let str3 = deepClone(str1);

console.log(str3 === str1); // false

console.log(str3.obj === str1.obj); // false

console.log(str3.fn === str1.fn); // true

复制代码


011.获取视口尺寸
==========

**需要在HTML文件中运行**

function getViewportOffset() {

if (window.innerWidth) {

return {

w: window.innerWidth,

h: window.innerHeight

}

} else {

// ie8及其以下

if (document.compatMode === "BackCompat") {

// 怪异模式

return {

w: document.body.clientWidth,

h: document.body.clientHeight

}

} else {

// 标准模式

return {

w: document.documentElement.clientWidth,

h: document.documentElement.clientHeight

}

}

}

}

复制代码


012.数字前补零
=========

/**

  • num为你想要进行填充的数字
  • length为你想要的数字长度

    */

//迭代方式实现

padding1=(num, length)=> {

for(let len = (num + "").length; len < length; len = num.length) {

num = "0" + num;

}

return num;

}

//递归方式实现

padding2=(num, length) =>{

if((num + "").length >= length) {

return num;

}

return padding2("0" + num, length)

}

//转为小数

padding3=(num, length)=> {

let decimal = num / Math.pow(10, length);

//toFixed指定保留几位小数

decimal = decimal.toFixed(length) + "";

return decimal.substr(decimal.indexOf(".")+1);

}

//填充截取法

padding4=(num, length)=> {

//这里用slice和substr均可

return (Array(length).join("0") + num).slice(-length);

}

//填充截取法

padding5=(num, length)=> {

let len = (num + "").length;

let diff = length+1 - len;

if(diff > 0) {

return Array(diff).join("0") + num;

}

return num;

}

复制代码


013.格式转换:base64转file
====================

/**

  • base64 base64
  • filename 转换后的文件名

    /

    base64ToFile = (base64, filename )=> {

    let arr = base64.split(‘,‘)

    let mime = arr[0].match(/难过.?);/)[1]

    let suffix = mime.split(‘/‘)[1] // 图片后缀

    let bstr = atob(arr[1])

    let n = bstr.length

    let u8arr = new Uint8Array(n)

    while (n--) {

    u8arr[n] = bstr.charCodeAt(n)

    }

    return new File([u8arr], ${filename}.${suffix}, { type: mime })

    }

    复制代码


014.格式转换:base64转blob
====================

base64ToBlob = base64 => {

let arr = base64.split(‘,‘),

mime = arr[0].match(/??.*?);/)[1],

bstr = atob(arr[1]),

n = bstr.length,

u8arr = new Uint8Array(n);

while (n--) {

u8arr[n] = bstr.charCodeAt(n);

}

return new Blob([u8arr], { type: mime });

};

复制代码


015.格式转换:blob转file
==================

blobToFile = (blob, fileName) => {

blob.lastModifiedDate = new Date();

blob.name = fileName;

return blob;

};

复制代码


016.格式转换:file转base64
====================

/**

  • file 图片文件
  • 返回图片的Base64数据

    */

    fileToBase64 = file => {

    let reader = new FileReader();

    reader.readAsDataURL(file);

    reader.onload = function (e) {

    return e.target.result

    };

    }

    复制代码


017.获取地址栏传递过来的参数
================

/**

  • name为地址栏传递过来的字段名

    /

    getQueryString = name => {

    let reg = new RegExp("(^|&)" + name + "=([^&])(&|$)");

    let r = window.location.search.substr(1).match(reg);

    if (r != null) return unescape(r[2]); return null;

    }

// 测试

// http://localhost:3306/admin?id=111&name=xxx

// console.log(getQueryString(‘id‘)); // 111

// console.log(getQueryString(‘name‘)); // xxx

复制代码


018.对象处理为数组对象
=============

/**

  • obj 需要处理的对象

    */

    objToArrObj = obj => {

    let arr = []

    for(let i in obj){

    arr.push({[i]:obj[i]})

    }

    return arr

    }

// 测试数据

let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}

console.log(objToArrObj(obj));

/*

[

{ 20180410: 5 },

{ 20180411: 13 },

{ 20180412: 26 },

{ 20180413: 16 }

]

*/

  

![手把手教你常用JS方法封装(一) [ 大杂烩 ]](http://p3.pstatp.com/large/dfic-imagehandler/a3548031-8354-4d74-a3c5-dd39f97e2390)

持续更新中...
========

常用JS方法封装方法预告:

*   项目常用JS方法封装(二) [ 时间处理 ]
*   项目常用JS方法封装(三) [ 字符串相关处理 ]
*   项目常用JS方法封装(四) [ 数组相关处理 ]

* * *

**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**

001.输入一个值,返回其数据类型
=================

type = para => {

return Object.prototype.toString.call(para).slice(8,-1)

}

复制代码


002.阶乘
======

factorial = num => {

let count = 1;

for (let i = 1; i <= num; i++) {

count *= i;

}

return count;

}

复制代码


003.两个数之间累乘
===========

multBetride = (x, y) => {

let count;

if (x < y) {

count = x;

for (let i = x + 1; i <= y; i++) {

count *= i;

}

return count;

} else {

count = y;

for (let i = y + 1; i <= x; i++) {

count *= i;

}

return count;

}

}

复制代码


004.累加
======

()里面可以放N个实参

function cumsum() {

let sum = 0;

for (let i = 0; i < arguments.length; i++) {

sum += arguments[i];

}

return sum;

}

复制代码


005.计时器(计算代码块(函数)执行时间)
======================

**无参 computeTime(f)**

computeTime = code => {

let startTime = new Date().getTime();

code();

let endTime = new Date().getTime();

let time = endTime - startTime;

return time;

}

复制代码


**有参 computeTime(f)** 使用方法:computeTime(f,参数1,参数2......)

computeTime = f => {

let startTime = new Date().getTime();

let p = [];

for (let i = 1; i < arguments.length; i++) {

p.push(arguments[i])

}

f.apply(null, p)

let endTime = new Date().getTime();

let Time = endTime - startTime;

return Time;

}

复制代码


006.数字超过9显示省略号
==============

num_filter = val =>{

val = val?val-0:0;

if (val > 9 ) {

return "…"

}else{

return val;

}

}

复制代码


007.数字超过99显示99+
===============

ninenum_filter = val =>{

val = val?val-0:0;

if (val > 99 ) {

return "99+"

}else{

return val;

}

}

复制代码


008.银行卡号分割
==========

bank_filter = val =>{

val += ‘‘;

val = val.replace(/(\s)/g,‘‘).replace(/(\d{4})/g,‘$1 ‘).replace(/\s*$/,‘‘);

return val;

}

复制代码


009.防抖与节流
=========

/**

  • 函数防抖 (只执行最后一次点击)

    /

    Debounce = (fn, t) => {

    let delay = t || 500;

    let timer;

    return function () {

    let args = arguments;

    if(timer){

    clearTimeout(timer);

    }

    timer = setTimeout(() => {

    timer = null;

    fn.apply(this, args);

    }, delay);

    }

    };

    /

  • 函数节流

    */

    Throttle = (fn, t) => {

    let last;

    let timer;

    let interval = t || 500;

    return function () {

    let args = arguments;

    let now = +new Date();

    if (last && now - last < interval) {

    clearTimeout(timer);

    timer = setTimeout(() => {

    last = now;

    fn.apply(this, args);

    }, interval);

    } else {

    last = now;

    fn.apply(this, args);

    }

    }

    };

复制代码


010.深拷贝
=======

deepClone = source => {

const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象

for (let keys in source) { // 遍历目标

if (source.hasOwnProperty(keys)) {

if (source[keys] && typeof source[keys] === ‘object‘) { // 如果值是对象,就递归一下

targetObj[keys] = source[keys].constructor === Array ? [] : {};

targetObj[keys] = deepClone(source[keys]);

} else { // 如果不是,就直接赋值

targetObj[keys] = source[keys];

}

}

}

return targetObj;

}

let str1 = {

arr: [1, 2, 3],

obj: {

key: ‘value‘

},

fn: function () {

return 1;

}

};

let str3 = deepClone(str1);

console.log(str3 === str1); // false

console.log(str3.obj === str1.obj); // false

console.log(str3.fn === str1.fn); // true

复制代码


011.获取视口尺寸
==========

**需要在HTML文件中运行**

function getViewportOffset() {

if (window.innerWidth) {

return {

w: window.innerWidth,

h: window.innerHeight

}

} else {

// ie8及其以下

if (document.compatMode === "BackCompat") {

// 怪异模式

return {

w: document.body.clientWidth,

h: document.body.clientHeight

}

} else {

// 标准模式

return {

w: document.documentElement.clientWidth,

h: document.documentElement.clientHeight

}

}

}

}

复制代码


012.数字前补零
=========

/**

  • num为你想要进行填充的数字
  • length为你想要的数字长度

    */

//迭代方式实现

padding1=(num, length)=> {

for(let len = (num + "").length; len < length; len = num.length) {

num = "0" + num;

}

return num;

}

//递归方式实现

padding2=(num, length) =>{

if((num + "").length >= length) {

return num;

}

return padding2("0" + num, length)

}

//转为小数

padding3=(num, length)=> {

let decimal = num / Math.pow(10, length);

//toFixed指定保留几位小数

decimal = decimal.toFixed(length) + "";

return decimal.substr(decimal.indexOf(".")+1);

}

//填充截取法

padding4=(num, length)=> {

//这里用slice和substr均可

return (Array(length).join("0") + num).slice(-length);

}

//填充截取法

padding5=(num, length)=> {

let len = (num + "").length;

let diff = length+1 - len;

if(diff > 0) {

return Array(diff).join("0") + num;

}

return num;

}

复制代码


013.格式转换:base64转file
====================

/**

  • base64 base64
  • filename 转换后的文件名

    /

    base64ToFile = (base64, filename )=> {

    let arr = base64.split(‘,‘)

    let mime = arr[0].match(/难过.?);/)[1]

    let suffix = mime.split(‘/‘)[1] // 图片后缀

    let bstr = atob(arr[1])

    let n = bstr.length

    let u8arr = new Uint8Array(n)

    while (n--) {

    u8arr[n] = bstr.charCodeAt(n)

    }

    return new File([u8arr], ${filename}.${suffix}, { type: mime })

    }

    复制代码


014.格式转换:base64转blob
====================

base64ToBlob = base64 => {

let arr = base64.split(‘,‘),

mime = arr[0].match(/??.*?);/)[1],

bstr = atob(arr[1]),

n = bstr.length,

u8arr = new Uint8Array(n);

while (n--) {

u8arr[n] = bstr.charCodeAt(n);

}

return new Blob([u8arr], { type: mime });

};

复制代码


015.格式转换:blob转file
==================

blobToFile = (blob, fileName) => {

blob.lastModifiedDate = new Date();

blob.name = fileName;

return blob;

};

复制代码


016.格式转换:file转base64
====================

/**

  • file 图片文件
  • 返回图片的Base64数据

    */

    fileToBase64 = file => {

    let reader = new FileReader();

    reader.readAsDataURL(file);

    reader.onload = function (e) {

    return e.target.result

    };

    }

    复制代码


017.获取地址栏传递过来的参数
================

/**

  • name为地址栏传递过来的字段名

    /

    getQueryString = name => {

    let reg = new RegExp("(^|&)" + name + "=([^&])(&|$)");

    let r = window.location.search.substr(1).match(reg);

    if (r != null) return unescape(r[2]); return null;

    }

// 测试

// http://localhost:3306/admin?id=111&name=xxx

// console.log(getQueryString(‘id‘)); // 111

// console.log(getQueryString(‘name‘)); // xxx

复制代码


018.对象处理为数组对象
=============

/**

  • obj 需要处理的对象

    */

    objToArrObj = obj => {

    let arr = []

    for(let i in obj){

    arr.push({[i]:obj[i]})

    }

    return arr

    }

// 测试数据

let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}

console.log(objToArrObj(obj));

/*

[

{ 20180410: 5 },

{ 20180411: 13 },

{ 20180412: 26 },

{ 20180413: 16 }

]

*/

  

![手把手教你常用JS方法封装(一) [ 大杂烩 ]](http://p3.pstatp.com/large/dfic-imagehandler/a3548031-8354-4d74-a3c5-dd39f97e2390)

持续更新中...
========

常用JS方法封装方法预告:

*   项目常用JS方法封装(二) [ 时间处理 ]
*   项目常用JS方法封装(三) [ 字符串相关处理 ]
*   项目常用JS方法封装(四) [ 数组相关处理 ]

* * *

**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**

001.输入一个值,返回其数据类型
=================

type = para => {

return Object.prototype.toString.call(para).slice(8,-1)

}

复制代码


002.阶乘
======

factorial = num => {

let count = 1;

for (let i = 1; i <= num; i++) {

count *= i;

}

return count;

}

复制代码


003.两个数之间累乘
===========

multBetride = (x, y) => {

let count;

if (x < y) {

count = x;

for (let i = x + 1; i <= y; i++) {

count *= i;

}

return count;

} else {

count = y;

for (let i = y + 1; i <= x; i++) {

count *= i;

}

return count;

}

}

复制代码


004.累加
======

()里面可以放N个实参

function cumsum() {

let sum = 0;

for (let i = 0; i < arguments.length; i++) {

sum += arguments[i];

}

return sum;

}

复制代码


005.计时器(计算代码块(函数)执行时间)
======================

**无参 computeTime(f)**

computeTime = code => {

let startTime = new Date().getTime();

code();

let endTime = new Date().getTime();

let time = endTime - startTime;

return time;

}

复制代码


**有参 computeTime(f)** 使用方法:computeTime(f,参数1,参数2......)

computeTime = f => {

let startTime = new Date().getTime();

let p = [];

for (let i = 1; i < arguments.length; i++) {

p.push(arguments[i])

}

f.apply(null, p)

let endTime = new Date().getTime();

let Time = endTime - startTime;

return Time;

}

复制代码


006.数字超过9显示省略号
==============

num_filter = val =>{

val = val?val-0:0;

if (val > 9 ) {

return "…"

}else{

return val;

}

}

复制代码


007.数字超过99显示99+
===============

ninenum_filter = val =>{

val = val?val-0:0;

if (val > 99 ) {

return "99+"

}else{

return val;

}

}

复制代码


008.银行卡号分割
==========

bank_filter = val =>{

val += ‘‘;

val = val.replace(/(\s)/g,‘‘).replace(/(\d{4})/g,‘$1 ‘).replace(/\s*$/,‘‘);

return val;

}

复制代码


009.防抖与节流
=========

/**

  • 函数防抖 (只执行最后一次点击)

    /

    Debounce = (fn, t) => {

    let delay = t || 500;

    let timer;

    return function () {

    let args = arguments;

    if(timer){

    clearTimeout(timer);

    }

    timer = setTimeout(() => {

    timer = null;

    fn.apply(this, args);

    }, delay);

    }

    };

    /

  • 函数节流

    */

    Throttle = (fn, t) => {

    let last;

    let timer;

    let interval = t || 500;

    return function () {

    let args = arguments;

    let now = +new Date();

    if (last && now - last < interval) {

    clearTimeout(timer);

    timer = setTimeout(() => {

    last = now;

    fn.apply(this, args);

    }, interval);

    } else {

    last = now;

    fn.apply(this, args);

    }

    }

    };

复制代码


010.深拷贝
=======

deepClone = source => {

const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象

for (let keys in source) { // 遍历目标

if (source.hasOwnProperty(keys)) {

if (source[keys] && typeof source[keys] === ‘object‘) { // 如果值是对象,就递归一下

targetObj[keys] = source[keys].constructor === Array ? [] : {};

targetObj[keys] = deepClone(source[keys]);

} else { // 如果不是,就直接赋值

targetObj[keys] = source[keys];

}

}

}

return targetObj;

}

let str1 = {

arr: [1, 2, 3],

obj: {

key: ‘value‘

},

fn: function () {

return 1;

}

};

let str3 = deepClone(str1);

console.log(str3 === str1); // false

console.log(str3.obj === str1.obj); // false

console.log(str3.fn === str1.fn); // true

复制代码


011.获取视口尺寸
==========

**需要在HTML文件中运行**

function getViewportOffset() {

if (window.innerWidth) {

return {

w: window.innerWidth,

h: window.innerHeight

}

} else {

// ie8及其以下

if (document.compatMode === "BackCompat") {

// 怪异模式

return {

w: document.body.clientWidth,

h: document.body.clientHeight

}

} else {

// 标准模式

return {

w: document.documentElement.clientWidth,

h: document.documentElement.clientHeight

}

}

}

}

复制代码


012.数字前补零
=========

/**

  • num为你想要进行填充的数字
  • length为你想要的数字长度

    */

//迭代方式实现

padding1=(num, length)=> {

for(let len = (num + "").length; len < length; len = num.length) {

num = "0" + num;

}

return num;

}

//递归方式实现

padding2=(num, length) =>{

if((num + "").length >= length) {

return num;

}

return padding2("0" + num, length)

}

//转为小数

padding3=(num, length)=> {

let decimal = num / Math.pow(10, length);

//toFixed指定保留几位小数

decimal = decimal.toFixed(length) + "";

return decimal.substr(decimal.indexOf(".")+1);

}

//填充截取法

padding4=(num, length)=> {

//这里用slice和substr均可

return (Array(length).join("0") + num).slice(-length);

}

//填充截取法

padding5=(num, length)=> {

let len = (num + "").length;

let diff = length+1 - len;

if(diff > 0) {

return Array(diff).join("0") + num;

}

return num;

}

复制代码


013.格式转换:base64转file
====================

/**

  • base64 base64
  • filename 转换后的文件名

    /

    base64ToFile = (base64, filename )=> {

    let arr = base64.split(‘,‘)

    let mime = arr[0].match(/难过.?);/)[1]

    let suffix = mime.split(‘/‘)[1] // 图片后缀

    let bstr = atob(arr[1])

    let n = bstr.length

    let u8arr = new Uint8Array(n)

    while (n--) {

    u8arr[n] = bstr.charCodeAt(n)

    }

    return new File([u8arr], ${filename}.${suffix}, { type: mime })

    }

    复制代码


014.格式转换:base64转blob
====================

base64ToBlob = base64 => {

let arr = base64.split(‘,‘),

mime = arr[0].match(/??.*?);/)[1],

bstr = atob(arr[1]),

n = bstr.length,

u8arr = new Uint8Array(n);

while (n--) {

u8arr[n] = bstr.charCodeAt(n);

}

return new Blob([u8arr], { type: mime });

};

复制代码


015.格式转换:blob转file
==================

blobToFile = (blob, fileName) => {

blob.lastModifiedDate = new Date();

blob.name = fileName;

return blob;

};

复制代码


016.格式转换:file转base64
====================

/**

  • file 图片文件
  • 返回图片的Base64数据

    */

    fileToBase64 = file => {

    let reader = new FileReader();

    reader.readAsDataURL(file);

    reader.onload = function (e) {

    return e.target.result

    };

    }

    复制代码


017.获取地址栏传递过来的参数
================

/**

  • name为地址栏传递过来的字段名

    /

    getQueryString = name => {

    let reg = new RegExp("(^|&)" + name + "=([^&])(&|$)");

    let r = window.location.search.substr(1).match(reg);

    if (r != null) return unescape(r[2]); return null;

    }

// 测试

// http://localhost:3306/admin?id=111&name=xxx

// console.log(getQueryString(‘id‘)); // 111

// console.log(getQueryString(‘name‘)); // xxx

复制代码


018.对象处理为数组对象
=============

/**

  • obj 需要处理的对象

    */

    objToArrObj = obj => {

    let arr = []

    for(let i in obj){

    arr.push({[i]:obj[i]})

    }

    return arr

    }

// 测试数据

let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}

console.log(objToArrObj(obj));

/*

[

{ 20180410: 5 },

{ 20180411: 13 },

{ 20180412: 26 },

{ 20180413: 16 }

]

*/

  

![手把手教你常用JS方法封装(一) [ 大杂烩 ]](http://p3.pstatp.com/large/dfic-imagehandler/a3548031-8354-4d74-a3c5-dd39f97e2390)

持续更新中...
========

常用JS方法封装方法预告:

*   项目常用JS方法封装(二) [ 时间处理 ]
*   项目常用JS方法封装(三) [ 字符串相关处理 ]
*   项目常用JS方法封装(四) [ 数组相关处理 ]

* * *

**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**

001.输入一个值,返回其数据类型
=================

type = para => {

return Object.prototype.toString.call(para).slice(8,-1)

}

复制代码


002.阶乘
======

factorial = num => {

let count = 1;

for (let i = 1; i <= num; i++) {

count *= i;

}

return count;

}

复制代码


003.两个数之间累乘
===========

multBetride = (x, y) => {

let count;

if (x < y) {

count = x;

for (let i = x + 1; i <= y; i++) {

count *= i;

}

return count;

} else {

count = y;

for (let i = y + 1; i <= x; i++) {

count *= i;

}

return count;

}

}

复制代码


004.累加
======

()里面可以放N个实参

function cumsum() {

let sum = 0;

for (let i = 0; i < arguments.length; i++) {

sum += arguments[i];

}

return sum;

}

复制代码


005.计时器(计算代码块(函数)执行时间)
======================

**无参 computeTime(f)**

computeTime = code => {

let startTime = new Date().getTime();

code();

let endTime = new Date().getTime();

let time = endTime - startTime;

return time;

}

复制代码


**有参 computeTime(f)** 使用方法:computeTime(f,参数1,参数2......)

computeTime = f => {

let startTime = new Date().getTime();

let p = [];

for (let i = 1; i < arguments.length; i++) {

p.push(arguments[i])

}

f.apply(null, p)

let endTime = new Date().getTime();

let Time = endTime - startTime;

return Time;

}

复制代码


006.数字超过9显示省略号
==============

num_filter = val =>{

val = val?val-0:0;

if (val > 9 ) {

return "…"

}else{

return val;

}

}

复制代码


007.数字超过99显示99+
===============

ninenum_filter = val =>{

val = val?val-0:0;

if (val > 99 ) {

return "99+"

}else{

return val;

}

}

复制代码


008.银行卡号分割
==========

bank_filter = val =>{

val += ‘‘;

val = val.replace(/(\s)/g,‘‘).replace(/(\d{4})/g,‘$1 ‘).replace(/\s*$/,‘‘);

return val;

}

复制代码


009.防抖与节流
=========

/**

  • 函数防抖 (只执行最后一次点击)

    /

    Debounce = (fn, t) => {

    let delay = t || 500;

    let timer;

    return function () {

    let args = arguments;

    if(timer){

    clearTimeout(timer);

    }

    timer = setTimeout(() => {

    timer = null;

    fn.apply(this, args);

    }, delay);

    }

    };

    /

  • 函数节流

    */

    Throttle = (fn, t) => {

    let last;

    let timer;

    let interval = t || 500;

    return function () {

    let args = arguments;

    let now = +new Date();

    if (last && now - last < interval) {

    clearTimeout(timer);

    timer = setTimeout(() => {

    last = now;

    fn.apply(this, args);

    }, interval);

    } else {

    last = now;

    fn.apply(this, args);

    }

    }

    };

复制代码


010.深拷贝
=======

deepClone = source => {

const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象

for (let keys in source) { // 遍历目标

if (source.hasOwnProperty(keys)) {

if (source[keys] && typeof source[keys] === ‘object‘) { // 如果值是对象,就递归一下

targetObj[keys] = source[keys].constructor === Array ? [] : {};

targetObj[keys] = deepClone(source[keys]);

} else { // 如果不是,就直接赋值

targetObj[keys] = source[keys];

}

}

}

return targetObj;

}

let str1 = {

arr: [1, 2, 3],

obj: {

key: ‘value‘

},

fn: function () {

return 1;

}

};

let str3 = deepClone(str1);

console.log(str3 === str1); // false

console.log(str3.obj === str1.obj); // false

console.log(str3.fn === str1.fn); // true

复制代码


011.获取视口尺寸
==========

**需要在HTML文件中运行**

function getViewportOffset() {

if (window.innerWidth) {

return {

w: window.innerWidth,

h: window.innerHeight

}

} else {

// ie8及其以下

if (document.compatMode === "BackCompat") {

// 怪异模式

return {

w: document.body.clientWidth,

h: document.body.clientHeight

}

} else {

// 标准模式

return {

w: document.documentElement.clientWidth,

h: document.documentElement.clientHeight

}

}

}

}

复制代码


012.数字前补零
=========

/**

  • num为你想要进行填充的数字
  • length为你想要的数字长度

    */

//迭代方式实现

padding1=(num, length)=> {

for(let len = (num + "").length; len < length; len = num.length) {

num = "0" + num;

}

return num;

}

//递归方式实现

padding2=(num, length) =>{

if((num + "").length >= length) {

return num;

}

return padding2("0" + num, length)

}

//转为小数

padding3=(num, length)=> {

let decimal = num / Math.pow(10, length);

//toFixed指定保留几位小数

decimal = decimal.toFixed(length) + "";

return decimal.substr(decimal.indexOf(".")+1);

}

//填充截取法

padding4=(num, length)=> {

//这里用slice和substr均可

return (Array(length).join("0") + num).slice(-length);

}

//填充截取法

padding5=(num, length)=> {

let len = (num + "").length;

let diff = length+1 - len;

if(diff > 0) {

return Array(diff).join("0") + num;

}

return num;

}

复制代码


013.格式转换:base64转file
====================

/**

  • base64 base64
  • filename 转换后的文件名

    /

    base64ToFile = (base64, filename )=> {

    let arr = base64.split(‘,‘)

    let mime = arr[0].match(/难过.?);/)[1]

    let suffix = mime.split(‘/‘)[1] // 图片后缀

    let bstr = atob(arr[1])

    let n = bstr.length

    let u8arr = new Uint8Array(n)

    while (n--) {

    u8arr[n] = bstr.charCodeAt(n)

    }

    return new File([u8arr], ${filename}.${suffix}, { type: mime })

    }

    复制代码


014.格式转换:base64转blob
====================

base64ToBlob = base64 => {

let arr = base64.split(‘,‘),

mime = arr[0].match(/??.*?);/)[1],

bstr = atob(arr[1]),

n = bstr.length,

u8arr = new Uint8Array(n);

while (n--) {

u8arr[n] = bstr.charCodeAt(n);

}

return new Blob([u8arr], { type: mime });

};

复制代码


015.格式转换:blob转file
==================

blobToFile = (blob, fileName) => {

blob.lastModifiedDate = new Date();

blob.name = fileName;

return blob;

};

复制代码


016.格式转换:file转base64
====================

/**

  • file 图片文件
  • 返回图片的Base64数据

    */

    fileToBase64 = file => {

    let reader = new FileReader();

    reader.readAsDataURL(file);

    reader.onload = function (e) {

    return e.target.result

    };

    }

    复制代码


017.获取地址栏传递过来的参数
================

/**

  • name为地址栏传递过来的字段名

    /

    getQueryString = name => {

    let reg = new RegExp("(^|&)" + name + "=([^&])(&|$)");

    let r = window.location.search.substr(1).match(reg);

    if (r != null) return unescape(r[2]); return null;

    }

// 测试

// http://localhost:3306/admin?id=111&name=xxx

// console.log(getQueryString(‘id‘)); // 111

// console.log(getQueryString(‘name‘)); // xxx

复制代码


018.对象处理为数组对象
=============

/**

  • obj 需要处理的对象

    */

    objToArrObj = obj => {

    let arr = []

    for(let i in obj){

    arr.push({[i]:obj[i]})

    }

    return arr

    }

// 测试数据

let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}

console.log(objToArrObj(obj));

/*

[

{ 20180410: 5 },

{ 20180411: 13 },

{ 20180412: 26 },

{ 20180413: 16 }

]

*/

  

![手把手教你常用JS方法封装(一) [ 大杂烩 ]](http://p3.pstatp.com/large/dfic-imagehandler/a3548031-8354-4d74-a3c5-dd39f97e2390)

持续更新中...
========

常用JS方法封装方法预告:

*   项目常用JS方法封装(二) [ 时间处理 ]
*   项目常用JS方法封装(三) [ 字符串相关处理 ]
*   项目常用JS方法封装(四) [ 数组相关处理 ]

* * *

**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**

001.输入一个值,返回其数据类型
=================

type = para => {

return Object.prototype.toString.call(para).slice(8,-1)

}

复制代码


002.阶乘
======

factorial = num => {

let count = 1;

for (let i = 1; i <= num; i++) {

count *= i;

}

return count;

}

复制代码


003.两个数之间累乘
===========

multBetride = (x, y) => {

let count;

if (x < y) {

count = x;

for (let i = x + 1; i <= y; i++) {

count *= i;

}

return count;

} else {

count = y;

for (let i = y + 1; i <= x; i++) {

count *= i;

}

return count;

}

}

复制代码


004.累加
======

()里面可以放N个实参

function cumsum() {

let sum = 0;

for (let i = 0; i < arguments.length; i++) {

sum += arguments[i];

}

return sum;

}

复制代码


005.计时器(计算代码块(函数)执行时间)
======================

**无参 computeTime(f)**

computeTime = code => {

let startTime = new Date().getTime();

code();

let endTime = new Date().getTime();

let time = endTime - startTime;

return time;

}

复制代码


**有参 computeTime(f)** 使用方法:computeTime(f,参数1,参数2......)

computeTime = f => {

let startTime = new Date().getTime();

let p = [];

for (let i = 1; i < arguments.length; i++) {

p.push(arguments[i])

}

f.apply(null, p)

let endTime = new Date().getTime();

let Time = endTime - startTime;

return Time;

}

复制代码


006.数字超过9显示省略号
==============

num_filter = val =>{

val = val?val-0:0;

if (val > 9 ) {

return "…"

}else{

return val;

}

}

复制代码


007.数字超过99显示99+
===============

ninenum_filter = val =>{

val = val?val-0:0;

if (val > 99 ) {

return "99+"

}else{

return val;

}

}

复制代码


008.银行卡号分割
==========

bank_filter = val =>{

val += ‘‘;

val = val.replace(/(\s)/g,‘‘).replace(/(\d{4})/g,‘$1 ‘).replace(/\s*$/,‘‘);

return val;

}

复制代码


009.防抖与节流
=========

/**

  • 函数防抖 (只执行最后一次点击)

    /

    Debounce = (fn, t) => {

    let delay = t || 500;

    let timer;

    return function () {

    let args = arguments;

    if(timer){

    clearTimeout(timer);

    }

    timer = setTimeout(() => {

    timer = null;

    fn.apply(this, args);

    }, delay);

    }

    };

    /

  • 函数节流

    */

    Throttle = (fn, t) => {

    let last;

    let timer;

    let interval = t || 500;

    return function () {

    let args = arguments;

    let now = +new Date();

    if (last && now - last < interval) {

    clearTimeout(timer);

    timer = setTimeout(() => {

    last = now;

    fn.apply(this, args);

    }, interval);

    } else {

    last = now;

    fn.apply(this, args);

    }

    }

    };

复制代码


010.深拷贝
=======

deepClone = source => {

const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象

for (let keys in source) { // 遍历目标

if (source.hasOwnProperty(keys)) {

if (source[keys] && typeof source[keys] === ‘object‘) { // 如果值是对象,就递归一下

targetObj[keys] = source[keys].constructor === Array ? [] : {};

targetObj[keys] = deepClone(source[keys]);

} else { // 如果不是,就直接赋值

targetObj[keys] = source[keys];

}

}

}

return targetObj;

}

let str1 = {

arr: [1, 2, 3],

obj: {

key: ‘value‘

},

fn: function () {

return 1;

}

};

let str3 = deepClone(str1);

console.log(str3 === str1); // false

console.log(str3.obj === str1.obj); // false

console.log(str3.fn === str1.fn); // true

复制代码


011.获取视口尺寸
==========

**需要在HTML文件中运行**

function getViewportOffset() {

if (window.innerWidth) {

return {

w: window.innerWidth,

h: window.innerHeight

}

} else {

// ie8及其以下

if (document.compatMode === "BackCompat") {

// 怪异模式

return {

w: document.body.clientWidth,

h: document.body.clientHeight

}

} else {

// 标准模式

return {

w: document.documentElement.clientWidth,

h: document.documentElement.clientHeight

}

}

}

}

复制代码


012.数字前补零
=========

/**

  • num为你想要进行填充的数字
  • length为你想要的数字长度

    */

//迭代方式实现

padding1=(num, length)=> {

for(let len = (num + "").length; len < length; len = num.length) {

num = "0" + num;

}

return num;

}

//递归方式实现

padding2=(num, length) =>{

if((num + "").length >= length) {

return num;

}

return padding2("0" + num, length)

}

//转为小数

padding3=(num, length)=> {

let decimal = num / Math.pow(10, length);

//toFixed指定保留几位小数

decimal = decimal.toFixed(length) + "";

return decimal.substr(decimal.indexOf(".")+1);

}

//填充截取法

padding4=(num, length)=> {

//这里用slice和substr均可

return (Array(length).join("0") + num).slice(-length);

}

//填充截取法

padding5=(num, length)=> {

let len = (num + "").length;

let diff = length+1 - len;

if(diff > 0) {

return Array(diff).join("0") + num;

}

return num;

}

复制代码


013.格式转换:base64转file
====================

/**

  • base64 base64
  • filename 转换后的文件名

    /

    base64ToFile = (base64, filename )=> {

    let arr = base64.split(‘,‘)

    let mime = arr[0].match(/难过.?);/)[1]

    let suffix = mime.split(‘/‘)[1] // 图片后缀

    let bstr = atob(arr[1])

    let n = bstr.length

    let u8arr = new Uint8Array(n)

    while (n--) {

    u8arr[n] = bstr.charCodeAt(n)

    }

    return new File([u8arr], ${filename}.${suffix}, { type: mime })

    }

    复制代码


014.格式转换:base64转blob
====================

base64ToBlob = base64 => {

let arr = base64.split(‘,‘),

mime = arr[0].match(/??.*?);/)[1],

bstr = atob(arr[1]),

n = bstr.length,

u8arr = new Uint8Array(n);

while (n--) {

u8arr[n] = bstr.charCodeAt(n);

}

return new Blob([u8arr], { type: mime });

};

复制代码


015.格式转换:blob转file
==================

blobToFile = (blob, fileName) => {

blob.lastModifiedDate = new Date();

blob.name = fileName;

return blob;

};

复制代码


016.格式转换:file转base64
====================

/**

  • file 图片文件
  • 返回图片的Base64数据

    */

    fileToBase64 = file => {

    let reader = new FileReader();

    reader.readAsDataURL(file);

    reader.onload = function (e) {

    return e.target.result

    };

    }

    复制代码


017.获取地址栏传递过来的参数
================

/**

  • name为地址栏传递过来的字段名

    /

    getQueryString = name => {

    let reg = new RegExp("(^|&)" + name + "=([^&])(&|$)");

    let r = window.location.search.substr(1).match(reg);

    if (r != null) return unescape(r[2]); return null;

    }

// 测试

// http://localhost:3306/admin?id=111&name=xxx

// console.log(getQueryString(‘id‘)); // 111

// console.log(getQueryString(‘name‘)); // xxx

复制代码


018.对象处理为数组对象
=============

/**

  • obj 需要处理的对象

    */

    objToArrObj = obj => {

    let arr = []

    for(let i in obj){

    arr.push({[i]:obj[i]})

    }

    return arr

    }

// 测试数据

let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}

console.log(objToArrObj(obj));

/*

[

{ 20180410: 5 },

{ 20180411: 13 },

{ 20180412: 26 },

{ 20180413: 16 }

]

*/

  

![手把手教你常用JS方法封装(一) [ 大杂烩 ]](http://p3.pstatp.com/large/dfic-imagehandler/a3548031-8354-4d74-a3c5-dd39f97e2390)

持续更新中...
========

常用JS方法封装方法预告:

*   项目常用JS方法封装(二) [ 时间处理 ]
*   项目常用JS方法封装(三) [ 字符串相关处理 ]
*   项目常用JS方法封装(四) [ 数组相关处理 ]

* * *

**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**

001.输入一个值,返回其数据类型
=================

type = para => {

return Object.prototype.toString.call(para).slice(8,-1)

}

复制代码


002.阶乘
======

factorial = num => {

let count = 1;

for (let i = 1; i <= num; i++) {

count *= i;

}

return count;

}

复制代码


003.两个数之间累乘
===========

multBetride = (x, y) => {

let count;

if (x < y) {

count = x;

for (let i = x + 1; i <= y; i++) {

count *= i;

}

return count;

} else {

count = y;

for (let i = y + 1; i <= x; i++) {

count *= i;

}

return count;

}

}

复制代码


004.累加
======

()里面可以放N个实参

function cumsum() {

let sum = 0;

for (let i = 0; i < arguments.length; i++) {

sum += arguments[i];

}

return sum;

}

复制代码


005.计时器(计算代码块(函数)执行时间)
======================

**无参 computeTime(f)**

computeTime = code => {

let startTime = new Date().getTime();

code();

let endTime = new Date().getTime();

let time = endTime - startTime;

return time;

}

复制代码


**有参 computeTime(f)** 使用方法:computeTime(f,参数1,参数2......)

computeTime = f => {

let startTime = new Date().getTime();

let p = [];

for (let i = 1; i < arguments.length; i++) {

p.push(arguments[i])

}

f.apply(null, p)

let endTime = new Date().getTime();

let Time = endTime - startTime;

return Time;

}

复制代码


006.数字超过9显示省略号
==============

num_filter = val =>{

val = val?val-0:0;

if (val > 9 ) {

return "…"

}else{

return val;

}

}

复制代码


007.数字超过99显示99+
===============

ninenum_filter = val =>{

val = val?val-0:0;

if (val > 99 ) {

return "99+"

}else{

return val;

}

}

复制代码


008.银行卡号分割
==========

bank_filter = val =>{

val += ‘‘;

val = val.replace(/(\s)/g,‘‘).replace(/(\d{4})/g,‘$1 ‘).replace(/\s*$/,‘‘);

return val;

}

复制代码


009.防抖与节流
=========

/**

  • 函数防抖 (只执行最后一次点击)

    /

    Debounce = (fn, t) => {

    let delay = t || 500;

    let timer;

    return function () {

    let args = arguments;

    if(timer){

    clearTimeout(timer);

    }

    timer = setTimeout(() => {

    timer = null;

    fn.apply(this, args);

    }, delay);

    }

    };

    /

  • 函数节流

    */

    Throttle = (fn, t) => {

    let last;

    let timer;

    let interval = t || 500;

    return function () {

    let args = arguments;

    let now = +new Date();

    if (last && now - last < interval) {

    clearTimeout(timer);

    timer = setTimeout(() => {

    last = now;

    fn.apply(this, args);

    }, interval);

    } else {

    last = now;

    fn.apply(this, args);

    }

    }

    };

复制代码


010.深拷贝
=======

deepClone = source => {

const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象

for (let keys in source) { // 遍历目标

if (source.hasOwnProperty(keys)) {

if (source[keys] && typeof source[keys] === ‘object‘) { // 如果值是对象,就递归一下

targetObj[keys] = source[keys].constructor === Array ? [] : {};

targetObj[keys] = deepClone(source[keys]);

} else { // 如果不是,就直接赋值

targetObj[keys] = source[keys];

}

}

}

return targetObj;

}

let str1 = {

arr: [1, 2, 3],

obj: {

key: ‘value‘

},

fn: function () {

return 1;

}

};

let str3 = deepClone(str1);

console.log(str3 === str1); // false

console.log(str3.obj === str1.obj); // false

console.log(str3.fn === str1.fn); // true

复制代码


011.获取视口尺寸
==========

**需要在HTML文件中运行**

function getViewportOffset() {

if (window.innerWidth) {

return {

w: window.innerWidth,

h: window.innerHeight

}

} else {

// ie8及其以下

if (document.compatMode === "BackCompat") {

// 怪异模式

return {

w: document.body.clientWidth,

h: document.body.clientHeight

}

} else {

// 标准模式

return {

w: document.documentElement.clientWidth,

h: document.documentElement.clientHeight

}

}

}

}

复制代码


012.数字前补零
=========

/**

  • num为你想要进行填充的数字
  • length为你想要的数字长度

    */

//迭代方式实现

padding1=(num, length)=> {

for(let len = (num + "").length; len < length; len = num.length) {

num = "0" + num;

}

return num;

}

//递归方式实现

padding2=(num, length) =>{

if((num + "").length >= length) {

return num;

}

return padding2("0" + num, length)

}

//转为小数

padding3=(num, length)=> {

let decimal = num / Math.pow(10, length);

//toFixed指定保留几位小数

decimal = decimal.toFixed(length) + "";

return decimal.substr(decimal.indexOf(".")+1);

}

//填充截取法

padding4=(num, length)=> {

//这里用slice和substr均可

return (Array(length).join("0") + num).slice(-length);

}

//填充截取法

padding5=(num, length)=> {

let len = (num + "").length;

let diff = length+1 - len;

if(diff > 0) {

return Array(diff).join("0") + num;

}

return num;

}

复制代码


013.格式转换:base64转file
====================

/**

  • base64 base64
  • filename 转换后的文件名

    /

    base64ToFile = (base64, filename )=> {

    let arr = base64.split(‘,‘)

    let mime = arr[0].match(/难过.?);/)[1]

    let suffix = mime.split(‘/‘)[1] // 图片后缀

    let bstr = atob(arr[1])

    let n = bstr.length

    let u8arr = new Uint8Array(n)

    while (n--) {

    u8arr[n] = bstr.charCodeAt(n)

    }

    return new File([u8arr], ${filename}.${suffix}, { type: mime })

    }

    复制代码


014.格式转换:base64转blob
====================

base64ToBlob = base64 => {

let arr = base64.split(‘,‘),

mime = arr[0].match(/??.*?);/)[1],

bstr = atob(arr[1]),

n = bstr.length,

u8arr = new Uint8Array(n);

while (n--) {

u8arr[n] = bstr.charCodeAt(n);

}

return new Blob([u8arr], { type: mime });

};

复制代码


015.格式转换:blob转file
==================

blobToFile = (blob, fileName) => {

blob.lastModifiedDate = new Date();

blob.name = fileName;

return blob;

};

复制代码


016.格式转换:file转base64
====================

/**

  • file 图片文件
  • 返回图片的Base64数据

    */

    fileToBase64 = file => {

    let reader = new FileReader();

    reader.readAsDataURL(file);

    reader.onload = function (e) {

    return e.target.result

    };

    }

    复制代码


017.获取地址栏传递过来的参数
================

/**

  • name为地址栏传递过来的字段名

    /

    getQueryString = name => {

    let reg = new RegExp("(^|&)" + name + "=([^&])(&|$)");

    let r = window.location.search.substr(1).match(reg);

    if (r != null) return unescape(r[2]); return null;

    }

// 测试

// http://localhost:3306/admin?id=111&name=xxx

// console.log(getQueryString(‘id‘)); // 111

// console.log(getQueryString(‘name‘)); // xxx

复制代码


018.对象处理为数组对象
=============

/**

  • obj 需要处理的对象

    */

    objToArrObj = obj => {

    let arr = []

    for(let i in obj){

    arr.push({[i]:obj[i]})

    }

    return arr

    }

// 测试数据

let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}

console.log(objToArrObj(obj));

/*

[

{ 20180410: 5 },

{ 20180411: 13 },

{ 20180412: 26 },

{ 20180413: 16 }

]

*/

  

![手把手教你常用JS方法封装(一) [ 大杂烩 ]](http://p3.pstatp.com/large/dfic-imagehandler/a3548031-8354-4d74-a3c5-dd39f97e2390)

持续更新中...
========

常用JS方法封装方法预告:

*   项目常用JS方法封装(二) [ 时间处理 ]
*   项目常用JS方法封装(三) [ 字符串相关处理 ]
*   项目常用JS方法封装(四) [ 数组相关处理 ]

* * *

**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**

001.输入一个值,返回其数据类型
=================

type = para => {

return Object.prototype.toString.call(para).slice(8,-1)

}

复制代码


002.阶乘
======

factorial = num => {

let count = 1;

for (let i = 1; i <= num; i++) {

count *= i;

}

return count;

}

复制代码


003.两个数之间累乘
===========

multBetride = (x, y) => {

let count;

if (x < y) {

count = x;

for (let i = x + 1; i <= y; i++) {

count *= i;

}

return count;

} else {

count = y;

for (let i = y + 1; i <= x; i++) {

count *= i;

}

return count;

}

}

复制代码


004.累加
======

()里面可以放N个实参

function cumsum() {

let sum = 0;

for (let i = 0; i < arguments.length; i++) {

sum += arguments[i];

}

return sum;

}

复制代码


005.计时器(计算代码块(函数)执行时间)
======================

**无参 computeTime(f)**

computeTime = code => {

let startTime = new Date().getTime();

code();

let endTime = new Date().getTime();

let time = endTime - startTime;

return time;

}

复制代码


**有参 computeTime(f)** 使用方法:computeTime(f,参数1,参数2......)

computeTime = f => {

let startTime = new Date().getTime();

let p = [];

for (let i = 1; i < arguments.length; i++) {

p.push(arguments[i])

}

f.apply(null, p)

let endTime = new Date().getTime();

let Time = endTime - startTime;

return Time;

}

复制代码


006.数字超过9显示省略号
==============

num_filter = val =>{

val = val?val-0:0;

if (val > 9 ) {

return "…"

}else{

return val;

}

}

复制代码


007.数字超过99显示99+
===============

ninenum_filter = val =>{

val = val?val-0:0;

if (val > 99 ) {

return "99+"

}else{

return val;

}

}

复制代码


008.银行卡号分割
==========

bank_filter = val =>{

val += ‘‘;

val = val.replace(/(\s)/g,‘‘).replace(/(\d{4})/g,‘$1 ‘).replace(/\s*$/,‘‘);

return val;

}

复制代码


009.防抖与节流
=========

/**

  • 函数防抖 (只执行最后一次点击)

    /

    Debounce = (fn, t) => {

    let delay = t || 500;

    let timer;

    return function () {

    let args = arguments;

    if(timer){

    clearTimeout(timer);

    }

    timer = setTimeout(() => {

    timer = null;

    fn.apply(this, args);

    }, delay);

    }

    };

    /

  • 函数节流

    */

    Throttle = (fn, t) => {

    let last;

    let timer;

    let interval = t || 500;

    return function () {

    let args = arguments;

    let now = +new Date();

    if (last && now - last < interval) {

    clearTimeout(timer);

    timer = setTimeout(() => {

    last = now;

    fn.apply(this, args);

    }, interval);

    } else {

    last = now;

    fn.apply(this, args);

    }

    }

    };

复制代码


010.深拷贝
=======

deepClone = source => {

const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象

for (let keys in source) { // 遍历目标

if (source.hasOwnProperty(keys)) {

if (source[keys] && typeof source[keys] === ‘object‘) { // 如果值是对象,就递归一下

targetObj[keys] = source[keys].constructor === Array ? [] : {};

targetObj[keys] = deepClone(source[keys]);

} else { // 如果不是,就直接赋值

targetObj[keys] = source[keys];

}

}

}

return targetObj;

}

let str1 = {

arr: [1, 2, 3],

obj: {

key: ‘value‘

},

fn: function () {

return 1;

}

};

let str3 = deepClone(str1);

console.log(str3 === str1); // false

console.log(str3.obj === str1.obj); // false

console.log(str3.fn === str1.fn); // true

复制代码


011.获取视口尺寸
==========

**需要在HTML文件中运行**

function getViewportOffset() {

if (window.innerWidth) {

return {

w: window.innerWidth,

h: window.innerHeight

}

} else {

// ie8及其以下

if (document.compatMode === "BackCompat") {

// 怪异模式

return {

w: document.body.clientWidth,

h: document.body.clientHeight

}

} else {

// 标准模式

return {

w: document.documentElement.clientWidth,

h: document.documentElement.clientHeight

}

}

}

}

复制代码


012.数字前补零
=========

/**

  • num为你想要进行填充的数字
  • length为你想要的数字长度

    */

//迭代方式实现

padding1=(num, length)=> {

for(let len = (num + "").length; len < length; len = num.length) {

num = "0" + num;

}

return num;

}

//递归方式实现

padding2=(num, length) =>{

if((num + "").length >= length) {

return num;

}

return padding2("0" + num, length)

}

//转为小数

padding3=(num, length)=> {

let decimal = num / Math.pow(10, length);

//toFixed指定保留几位小数

decimal = decimal.toFixed(length) + "";

return decimal.substr(decimal.indexOf(".")+1);

}

//填充截取法

padding4=(num, length)=> {

//这里用slice和substr均可

return (Array(length).join("0") + num).slice(-length);

}

//填充截取法

padding5=(num, length)=> {

let len = (num + "").length;

let diff = length+1 - len;

if(diff > 0) {

return Array(diff).join("0") + num;

}

return num;

}

复制代码


013.格式转换:base64转file
====================

/**

  • base64 base64
  • filename 转换后的文件名

    /

    base64ToFile = (base64, filename )=> {

    let arr = base64.split(‘,‘)

    let mime = arr[0].match(/难过.?);/)[1]

    let suffix = mime.split(‘/‘)[1] // 图片后缀

    let bstr = atob(arr[1])

    let n = bstr.length

    let u8arr = new Uint8Array(n)

    while (n--) {

    u8arr[n] = bstr.charCodeAt(n)

    }

    return new File([u8arr], ${filename}.${suffix}, { type: mime })

    }

    复制代码


014.格式转换:base64转blob
====================

base64ToBlob = base64 => {

let arr = base64.split(‘,‘),

mime = arr[0].match(/??.*?);/)[1],

bstr = atob(arr[1]),

n = bstr.length,

u8arr = new Uint8Array(n);

while (n--) {

u8arr[n] = bstr.charCodeAt(n);

}

return new Blob([u8arr], { type: mime });

};

复制代码


015.格式转换:blob转file
==================

blobToFile = (blob, fileName) => {

blob.lastModifiedDate = new Date();

blob.name = fileName;

return blob;

};

复制代码


016.格式转换:file转base64
====================

/**

  • file 图片文件
  • 返回图片的Base64数据

    */

    fileToBase64 = file => {

    let reader = new FileReader();

    reader.readAsDataURL(file);

    reader.onload = function (e) {

    return e.target.result

    };

    }

    复制代码


017.获取地址栏传递过来的参数
================

/**

  • name为地址栏传递过来的字段名

    /

    getQueryString = name => {

    let reg = new RegExp("(^|&)" + name + "=([^&])(&|$)");

    let r = window.location.search.substr(1).match(reg);

    if (r != null) return unescape(r[2]); return null;

    }

// 测试

// http://localhost:3306/admin?id=111&name=xxx

// console.log(getQueryString(‘id‘)); // 111

// console.log(getQueryString(‘name‘)); // xxx

复制代码


018.对象处理为数组对象
=============

/**

  • obj 需要处理的对象

    */

    objToArrObj = obj => {

    let arr = []

    for(let i in obj){

    arr.push({[i]:obj[i]})

    }

    return arr

    }

// 测试数据

let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}

console.log(objToArrObj(obj));

/*

[

{ 20180410: 5 },

{ 20180411: 13 },

{ 20180412: 26 },

{ 20180413: 16 }

]

*/

  

![手把手教你常用JS方法封装(一) [ 大杂烩 ]](http://p3.pstatp.com/large/dfic-imagehandler/a3548031-8354-4d74-a3c5-dd39f97e2390)

持续更新中...
========

常用JS方法封装方法预告:

*   项目常用JS方法封装(二) [ 时间处理 ]
*   项目常用JS方法封装(三) [ 字符串相关处理 ]
*   项目常用JS方法封装(四) [ 数组相关处理 ]

* * *

**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**

001.输入一个值,返回其数据类型
=================

type = para => {

return Object.prototype.toString.call(para).slice(8,-1)

}

复制代码


002.阶乘
======

factorial = num => {

let count = 1;

for (let i = 1; i <= num; i++) {

count *= i;

}

return count;

}

复制代码


003.两个数之间累乘
===========

multBetride = (x, y) => {

let count;

if (x < y) {

count = x;

for (let i = x + 1; i <= y; i++) {

count *= i;

}

return count;

} else {

count = y;

for (let i = y + 1; i <= x; i++) {

count *= i;

}

return count;

}

}

复制代码


004.累加
======

()里面可以放N个实参

function cumsum() {

let sum = 0;

for (let i = 0; i < arguments.length; i++) {

sum += arguments[i];

}

return sum;

}

复制代码


005.计时器(计算代码块(函数)执行时间)
======================

**无参 computeTime(f)**

computeTime = code => {

let startTime = new Date().getTime();

code();

let endTime = new Date().getTime();

let time = endTime - startTime;

return time;

}

复制代码


**有参 computeTime(f)** 使用方法:computeTime(f,参数1,参数2......)

computeTime = f => {

let startTime = new Date().getTime();

let p = [];

for (let i = 1; i < arguments.length; i++) {

p.push(arguments[i])

}

f.apply(null, p)

let endTime = new Date().getTime();

let Time = endTime - startTime;

return Time;

}

复制代码


006.数字超过9显示省略号
==============

num_filter = val =>{

val = val?val-0:0;

if (val > 9 ) {

return "…"

}else{

return val;

}

}

复制代码


007.数字超过99显示99+
===============

ninenum_filter = val =>{

val = val?val-0:0;

if (val > 99 ) {

return "99+"

}else{

return val;

}

}

复制代码


008.银行卡号分割
==========

bank_filter = val =>{

val += ‘‘;

val = val.replace(/(\s)/g,‘‘).replace(/(\d{4})/g,‘$1 ‘).replace(/\s*$/,‘‘);

return val;

}

复制代码


009.防抖与节流
=========

/**

  • 函数防抖 (只执行最后一次点击)

    /

    Debounce = (fn, t) => {

    let delay = t || 500;

    let timer;

    return function () {

    let args = arguments;

    if(timer){

    clearTimeout(timer);

    }

    timer = setTimeout(() => {

    timer = null;

    fn.apply(this, args);

    }, delay);

    }

    };

    /

  • 函数节流

    */

    Throttle = (fn, t) => {

    let last;

    let timer;

    let interval = t || 500;

    return function () {

    let args = arguments;

    let now = +new Date();

    if (last && now - last < interval) {

    clearTimeout(timer);

    timer = setTimeout(() => {

    last = now;

    fn.apply(this, args);

    }, interval);

    } else {

    last = now;

    fn.apply(this, args);

    }

    }

    };

复制代码


010.深拷贝
=======

deepClone = source => {

const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象

for (let keys in source) { // 遍历目标

if (source.hasOwnProperty(keys)) {

if (source[keys] && typeof source[keys] === ‘object‘) { // 如果值是对象,就递归一下

targetObj[keys] = source[keys].constructor === Array ? [] : {};

targetObj[keys] = deepClone(source[keys]);

} else { // 如果不是,就直接赋值

targetObj[keys] = source[keys];

}

}

}

return targetObj;

}

let str1 = {

arr: [1, 2, 3],

obj: {

key: ‘value‘

},

fn: function () {

return 1;

}

};

let str3 = deepClone(str1);

console.log(str3 === str1); // false

console.log(str3.obj === str1.obj); // false

console.log(str3.fn === str1.fn); // true

复制代码


011.获取视口尺寸
==========

**需要在HTML文件中运行**

function getViewportOffset() {

if (window.innerWidth) {

return {

w: window.innerWidth,

h: window.innerHeight

}

} else {

// ie8及其以下

if (document.compatMode === "BackCompat") {

// 怪异模式

return {

w: document.body.clientWidth,

h: document.body.clientHeight

}

} else {

// 标准模式

return {

w: document.documentElement.clientWidth,

h: document.documentElement.clientHeight

}

}

}

}

复制代码


012.数字前补零
=========

/**

  • num为你想要进行填充的数字
  • length为你想要的数字长度

    */

//迭代方式实现

padding1=(num, length)=> {

for(let len = (num + "").length; len < length; len = num.length) {

num = "0" + num;

}

return num;

}

//递归方式实现

padding2=(num, length) =>{

if((num + "").length >= length) {

return num;

}

return padding2("0" + num, length)

}

//转为小数

padding3=(num, length)=> {

let decimal = num / Math.pow(10, length);

//toFixed指定保留几位小数

decimal = decimal.toFixed(length) + "";

return decimal.substr(decimal.indexOf(".")+1);

}

//填充截取法

padding4=(num, length)=> {

//这里用slice和substr均可

return (Array(length).join("0") + num).slice(-length);

}

//填充截取法

padding5=(num, length)=> {

let len = (num + "").length;

let diff = length+1 - len;

if(diff > 0) {

return Array(diff).join("0") + num;

}

return num;

}

复制代码


013.格式转换:base64转file
====================

/**

  • base64 base64
  • filename 转换后的文件名

    /

    base64ToFile = (base64, filename )=> {

    let arr = base64.split(‘,‘)

    let mime = arr[0].match(/难过.?);/)[1]

    let suffix = mime.split(‘/‘)[1] // 图片后缀

    let bstr = atob(arr[1])

    let n = bstr.length

    let u8arr = new Uint8Array(n)

    while (n--) {

    u8arr[n] = bstr.charCodeAt(n)

    }

    return new File([u8arr], ${filename}.${suffix}, { type: mime })

    }

    复制代码


014.格式转换:base64转blob
====================

base64ToBlob = base64 => {

let arr = base64.split(‘,‘),

mime = arr[0].match(/??.*?);/)[1],

bstr = atob(arr[1]),

n = bstr.length,

u8arr = new Uint8Array(n);

while (n--) {

u8arr[n] = bstr.charCodeAt(n);

}

return new Blob([u8arr], { type: mime });

};

复制代码


015.格式转换:blob转file
==================

blobToFile = (blob, fileName) => {

blob.lastModifiedDate = new Date();

blob.name = fileName;

return blob;

};

复制代码


016.格式转换:file转base64
====================

/**

  • file 图片文件
  • 返回图片的Base64数据

    */

    fileToBase64 = file => {

    let reader = new FileReader();

    reader.readAsDataURL(file);

    reader.onload = function (e) {

    return e.target.result

    };

    }

    复制代码


017.获取地址栏传递过来的参数
================

/**

  • name为地址栏传递过来的字段名

    /

    getQueryString = name => {

    let reg = new RegExp("(^|&)" + name + "=([^&])(&|$)");

    let r = window.location.search.substr(1).match(reg);

    if (r != null) return unescape(r[2]); return null;

    }

// 测试

// http://localhost:3306/admin?id=111&name=xxx

// console.log(getQueryString(‘id‘)); // 111

// console.log(getQueryString(‘name‘)); // xxx

复制代码


018.对象处理为数组对象
=============

/**

  • obj 需要处理的对象

    */

    objToArrObj = obj => {

    let arr = []

    for(let i in obj){

    arr.push({[i]:obj[i]})

    }

    return arr

    }

// 测试数据

let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}

console.log(objToArrObj(obj));

/*

[

{ 20180410: 5 },

{ 20180411: 13 },

{ 20180412: 26 },

{ 20180413: 16 }

]

*/

  

![手把手教你常用JS方法封装(一) [ 大杂烩 ]](http://p3.pstatp.com/large/dfic-imagehandler/a3548031-8354-4d74-a3c5-dd39f97e2390)

持续更新中...
========

常用JS方法封装方法预告:

*   项目常用JS方法封装(二) [ 时间处理 ]
*   项目常用JS方法封装(三) [ 字符串相关处理 ]
*   项目常用JS方法封装(四) [ 数组相关处理 ]

* * *

**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**

001.输入一个值,返回其数据类型
=================

type = para => {

return Object.prototype.toString.call(para).slice(8,-1)

}

复制代码


002.阶乘
======

factorial = num => {

let count = 1;

for (let i = 1; i <= num; i++) {

count *= i;

}

return count;

}

复制代码


003.两个数之间累乘
===========

multBetride = (x, y) => {

let count;

if (x < y) {

count = x;

for (let i = x + 1; i <= y; i++) {

count *= i;

}

return count;

} else {

count = y;

for (let i = y + 1; i <= x; i++) {

count *= i;

}

return count;

}

}

复制代码


004.累加
======

()里面可以放N个实参

function cumsum() {

let sum = 0;

for (let i = 0; i < arguments.length; i++) {

sum += arguments[i];

}

return sum;

}

复制代码


005.计时器(计算代码块(函数)执行时间)
======================

**无参 computeTime(f)**

computeTime = code => {

let startTime = new Date().getTime();

code();

let endTime = new Date().getTime();

let time = endTime - startTime;

return time;

}

复制代码


**有参 computeTime(f)** 使用方法:computeTime(f,参数1,参数2......)

computeTime = f => {

let startTime = new Date().getTime();

let p = [];

for (let i = 1; i < arguments.length; i++) {

p.push(arguments[i])

}

f.apply(null, p)

let endTime = new Date().getTime();

let Time = endTime - startTime;

return Time;

}

复制代码


006.数字超过9显示省略号
==============

num_filter = val =>{

val = val?val-0:0;

if (val > 9 ) {

return "…"

}else{

return val;

}

}

复制代码


007.数字超过99显示99+
===============

ninenum_filter = val =>{

val = val?val-0:0;

if (val > 99 ) {

return "99+"

}else{

return val;

}

}

复制代码


008.银行卡号分割
==========

bank_filter = val =>{

val += ‘‘;

val = val.replace(/(\s)/g,‘‘).replace(/(\d{4})/g,‘$1 ‘).replace(/\s*$/,‘‘);

return val;

}

复制代码


009.防抖与节流
=========

/**

  • 函数防抖 (只执行最后一次点击)

    /

    Debounce = (fn, t) => {

    let delay = t || 500;

    let timer;

    return function () {

    let args = arguments;

    if(timer){

    clearTimeout(timer);

    }

    timer = setTimeout(() => {

    timer = null;

    fn.apply(this, args);

    }, delay);

    }

    };

    /

  • 函数节流

    */

    Throttle = (fn, t) => {

    let last;

    let timer;

    let interval = t || 500;

    return function () {

    let args = arguments;

    let now = +new Date();

    if (last && now - last < interval) {

    clearTimeout(timer);

    timer = setTimeout(() => {

    last = now;

    fn.apply(this, args);

    }, interval);

    } else {

    last = now;

    fn.apply(this, args);

    }

    }

    };

复制代码


010.深拷贝
=======

deepClone = source => {

const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象

for (let keys in source) { // 遍历目标

if (source.hasOwnProperty(keys)) {

if (source[keys] && typeof source[keys] === ‘object‘) { // 如果值是对象,就递归一下

targetObj[keys] = source[keys].constructor === Array ? [] : {};

targetObj[keys] = deepClone(source[keys]);

} else { // 如果不是,就直接赋值

targetObj[keys] = source[keys];

}

}

}

return targetObj;

}

let str1 = {

arr: [1, 2, 3],

obj: {

key: ‘value‘

},

fn: function () {

return 1;

}

};

let str3 = deepClone(str1);

console.log(str3 === str1); // false

console.log(str3.obj === str1.obj); // false

console.log(str3.fn === str1.fn); // true

复制代码


011.获取视口尺寸
==========

**需要在HTML文件中运行**

function getViewportOffset() {

if (window.innerWidth) {

return {

w: window.innerWidth,

h: window.innerHeight

}

} else {

// ie8及其以下

if (document.compatMode === "BackCompat") {

// 怪异模式

return {

w: document.body.clientWidth,

h: document.body.clientHeight

}

} else {

// 标准模式

return {

w: document.documentElement.clientWidth,

h: document.documentElement.clientHeight

}

}

}

}

复制代码


012.数字前补零
=========

/**

  • num为你想要进行填充的数字
  • length为你想要的数字长度

    */

//迭代方式实现

padding1=(num, length)=> {

for(let len = (num + "").length; len < length; len = num.length) {

num = "0" + num;

}

return num;

}

//递归方式实现

padding2=(num, length) =>{

if((num + "").length >= length) {

return num;

}

return padding2("0" + num, length)

}

//转为小数

padding3=(num, length)=> {

let decimal = num / Math.pow(10, length);

//toFixed指定保留几位小数

decimal = decimal.toFixed(length) + "";

return decimal.substr(decimal.indexOf(".")+1);

}

//填充截取法

padding4=(num, length)=> {

//这里用slice和substr均可

return (Array(length).join("0") + num).slice(-length);

}

//填充截取法

padding5=(num, length)=> {

let len = (num + "").length;

let diff = length+1 - len;

if(diff > 0) {

return Array(diff).join("0") + num;

}

return num;

}

复制代码


013.格式转换:base64转file
====================

/**

  • base64 base64
  • filename 转换后的文件名

    /

    base64ToFile = (base64, filename )=> {

    let arr = base64.split(‘,‘)

    let mime = arr[0].match(/难过.?);/)[1]

    let suffix = mime.split(‘/‘)[1] // 图片后缀

    let bstr = atob(arr[1])

    let n = bstr.length

    let u8arr = new Uint8Array(n)

    while (n--) {

    u8arr[n] = bstr.charCodeAt(n)

    }

    return new File([u8arr], ${filename}.${suffix}, { type: mime })

    }

    复制代码


014.格式转换:base64转blob
====================

base64ToBlob = base64 => {

let arr = base64.split(‘,‘),

mime = arr[0].match(/??.*?);/)[1],

bstr = atob(arr[1]),

n = bstr.length,

u8arr = new Uint8Array(n);

while (n--) {

u8arr[n] = bstr.charCodeAt(n);

}

return new Blob([u8arr], { type: mime });

};

复制代码


015.格式转换:blob转file
==================

blobToFile = (blob, fileName) => {

blob.lastModifiedDate = new Date();

blob.name = fileName;

return blob;

};

复制代码


016.格式转换:file转base64
====================

/**

  • file 图片文件
  • 返回图片的Base64数据

    */

    fileToBase64 = file => {

    let reader = new FileReader();

    reader.readAsDataURL(file);

    reader.onload = function (e) {

    return e.target.result

    };

    }

    复制代码


017.获取地址栏传递过来的参数
================

/**

  • name为地址栏传递过来的字段名

    /

    getQueryString = name => {

    let reg = new RegExp("(^|&)" + name + "=([^&])(&|$)");

    let r = window.location.search.substr(1).match(reg);

    if (r != null) return unescape(r[2]); return null;

    }

// 测试

// http://localhost:3306/admin?id=111&name=xxx

// console.log(getQueryString(‘id‘)); // 111

// console.log(getQueryString(‘name‘)); // xxx

复制代码


018.对象处理为数组对象
=============

/**

  • obj 需要处理的对象

    */

    objToArrObj = obj => {

    let arr = []

    for(let i in obj){

    arr.push({[i]:obj[i]})

    }

    return arr

    }

// 测试数据

let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}

console.log(objToArrObj(obj));

/*

[

{ 20180410: 5 },

{ 20180411: 13 },

{ 20180412: 26 },

{ 20180413: 16 }

]

*/

  

![手把手教你常用JS方法封装(一) [ 大杂烩 ]](http://p3.pstatp.com/large/dfic-imagehandler/a3548031-8354-4d74-a3c5-dd39f97e2390)

持续更新中...
========

常用JS方法封装方法预告:

*   项目常用JS方法封装(二) [ 时间处理 ]
*   项目常用JS方法封装(三) [ 字符串相关处理 ]
*   项目常用JS方法封装(四) [ 数组相关处理 ]

* * *

**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**

001.输入一个值,返回其数据类型
=================

type = para => {

return Object.prototype.toString.call(para).slice(8,-1)

}

复制代码


002.阶乘
======

factorial = num => {

let count = 1;

for (let i = 1; i <= num; i++) {

count *= i;

}

return count;

}

复制代码


003.两个数之间累乘
===========

multBetride = (x, y) => {

let count;

if (x < y) {

count = x;

for (let i = x + 1; i <= y; i++) {

count *= i;

}

return count;

} else {

count = y;

for (let i = y + 1; i <= x; i++) {

count *= i;

}

return count;

}

}

复制代码


004.累加
======

()里面可以放N个实参

function cumsum() {

let sum = 0;

for (let i = 0; i < arguments.length; i++) {

sum += arguments[i];

}

return sum;

}

复制代码


005.计时器(计算代码块(函数)执行时间)
======================

**无参 computeTime(f)**

computeTime = code => {

let startTime = new Date().getTime();

code();

let endTime = new Date().getTime();

let time = endTime - startTime;

return time;

}

复制代码


**有参 computeTime(f)** 使用方法:computeTime(f,参数1,参数2......)

computeTime = f => {

let startTime = new Date().getTime();

let p = [];

for (let i = 1; i < arguments.length; i++) {

p.push(arguments[i])

}

f.apply(null, p)

let endTime = new Date().getTime();

let Time = endTime - startTime;

return Time;

}

复制代码


006.数字超过9显示省略号
==============

num_filter = val =>{

val = val?val-0:0;

if (val > 9 ) {

return "…"

}else{

return val;

}

}

复制代码


007.数字超过99显示99+
===============

ninenum_filter = val =>{

val = val?val-0:0;

if (val > 99 ) {

return "99+"

}else{

return val;

}

}

复制代码


008.银行卡号分割
==========

bank_filter = val =>{

val += ‘‘;

val = val.replace(/(\s)/g,‘‘).replace(/(\d{4})/g,‘$1 ‘).replace(/\s*$/,‘‘);

return val;

}

复制代码


009.防抖与节流
=========

/**

  • 函数防抖 (只执行最后一次点击)

    /

    Debounce = (fn, t) => {

    let delay = t || 500;

    let timer;

    return function () {

    let args = arguments;

    if(timer){

    clearTimeout(timer);

    }

    timer = setTimeout(() => {

    timer = null;

    fn.apply(this, args);

    }, delay);

    }

    };

    /

  • 函数节流

    */

    Throttle = (fn, t) => {

    let last;

    let timer;

    let interval = t || 500;

    return function () {

    let args = arguments;

    let now = +new Date();

    if (last && now - last < interval) {

    clearTimeout(timer);

    timer = setTimeout(() => {

    last = now;

    fn.apply(this, args);

    }, interval);

    } else {

    last = now;

    fn.apply(this, args);

    }

    }

    };

复制代码


010.深拷贝
=======

deepClone = source => {

const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象

for (let keys in source) { // 遍历目标

if (source.hasOwnProperty(keys)) {

if (source[keys] && typeof source[keys] === ‘object‘) { // 如果值是对象,就递归一下

targetObj[keys] = source[keys].constructor === Array ? [] : {};

targetObj[keys] = deepClone(source[keys]);

} else { // 如果不是,就直接赋值

targetObj[keys] = source[keys];

}

}

}

return targetObj;

}

let str1 = {

arr: [1, 2, 3],

obj: {

key: ‘value‘

},

fn: function () {

return 1;

}

};

let str3 = deepClone(str1);

console.log(str3 === str1); // false

console.log(str3.obj === str1.obj); // false

console.log(str3.fn === str1.fn); // true

复制代码


011.获取视口尺寸
==========

**需要在HTML文件中运行**

function getViewportOffset() {

if (window.innerWidth) {

return {

w: window.innerWidth,

h: window.innerHeight

}

} else {

// ie8及其以下

if (document.compatMode === "BackCompat") {

// 怪异模式

return {

w: document.body.clientWidth,

h: document.body.clientHeight

}

} else {

// 标准模式

return {

w: document.documentElement.clientWidth,

h: document.documentElement.clientHeight

}

}

}

}

复制代码


012.数字前补零
=========

/**

  • num为你想要进行填充的数字
  • length为你想要的数字长度

    */

//迭代方式实现

padding1=(num, length)=> {

for(let len = (num + "").length; len < length; len = num.length) {

num = "0" + num;

}

return num;

}

//递归方式实现

padding2=(num, length) =>{

if((num + "").length >= length) {

return num;

}

return padding2("0" + num, length)

}

//转为小数

padding3=(num, length)=> {

let decimal = num / Math.pow(10, length);

//toFixed指定保留几位小数

decimal = decimal.toFixed(length) + "";

return decimal.substr(decimal.indexOf(".")+1);

}

//填充截取法

padding4=(num, length)=> {

//这里用slice和substr均可

return (Array(length).join("0") + num).slice(-length);

}

//填充截取法

padding5=(num, length)=> {

let len = (num + "").length;

let diff = length+1 - len;

if(diff > 0) {

return Array(diff).join("0") + num;

}

return num;

}

复制代码


013.格式转换:base64转file
====================

/**

  • base64 base64
  • filename 转换后的文件名

    /

    base64ToFile = (base64, filename )=> {

    let arr = base64.split(‘,‘)

    let mime = arr[0].match(/难过.?);/)[1]

    let suffix = mime.split(‘/‘)[1] // 图片后缀

    let bstr = atob(arr[1])

    let n = bstr.length

    let u8arr = new Uint8Array(n)

    while (n--) {

    u8arr[n] = bstr.charCodeAt(n)

    }

    return new File([u8arr], ${filename}.${suffix}, { type: mime })

    }

    复制代码


014.格式转换:base64转blob
====================

base64ToBlob = base64 => {

let arr = base64.split(‘,‘),

mime = arr[0].match(/??.*?);/)[1],

bstr = atob(arr[1]),

n = bstr.length,

u8arr = new Uint8Array(n);

while (n--) {

u8arr[n] = bstr.charCodeAt(n);

}

return new Blob([u8arr], { type: mime });

};

复制代码


015.格式转换:blob转file
==================

blobToFile = (blob, fileName) => {

blob.lastModifiedDate = new Date();

blob.name = fileName;

return blob;

};

复制代码


016.格式转换:file转base64
====================

/**

  • file 图片文件
  • 返回图片的Base64数据

    */

    fileToBase64 = file => {

    let reader = new FileReader();

    reader.readAsDataURL(file);

    reader.onload = function (e) {

    return e.target.result

    };

    }

    复制代码


017.获取地址栏传递过来的参数
================

/**

  • name为地址栏传递过来的字段名

    /

    getQueryString = name => {

    let reg = new RegExp("(^|&)" + name + "=([^&])(&|$)");

    let r = window.location.search.substr(1).match(reg);

    if (r != null) return unescape(r[2]); return null;

    }

// 测试

// http://localhost:3306/admin?id=111&name=xxx

// console.log(getQueryString(‘id‘)); // 111

// console.log(getQueryString(‘name‘)); // xxx

复制代码


018.对象处理为数组对象
=============

/**

  • obj 需要处理的对象

    */

    objToArrObj = obj => {

    let arr = []

    for(let i in obj){

    arr.push({[i]:obj[i]})

    }

    return arr

    }

// 测试数据

let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}

console.log(objToArrObj(obj));

/*

[

{ 20180410: 5 },

{ 20180411: 13 },

{ 20180412: 26 },

{ 20180413: 16 }

]

*/

  

![手把手教你常用JS方法封装(一) [ 大杂烩 ]](http://p3.pstatp.com/large/dfic-imagehandler/a3548031-8354-4d74-a3c5-dd39f97e2390)

持续更新中...
========

常用JS方法封装方法预告:

*   项目常用JS方法封装(二) [ 时间处理 ]
*   项目常用JS方法封装(三) [ 字符串相关处理 ]
*   项目常用JS方法封装(四) [ 数组相关处理 ]

* * *

**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**

001.输入一个值,返回其数据类型
=================

type = para => {

return Object.prototype.toString.call(para).slice(8,-1)

}

复制代码


002.阶乘
======

factorial = num => {

let count = 1;

for (let i = 1; i <= num; i++) {

count *= i;

}

return count;

}

复制代码


003.两个数之间累乘
===========

multBetride = (x, y) => {

let count;

if (x < y) {

count = x;

for (let i = x + 1; i <= y; i++) {

count *= i;

}

return count;

} else {

count = y;

for (let i = y + 1; i <= x; i++) {

count *= i;

}

return count;

}

}

复制代码


004.累加
======

()里面可以放N个实参

function cumsum() {

let sum = 0;

for (let i = 0; i < arguments.length; i++) {

sum += arguments[i];

}

return sum;

}

复制代码


005.计时器(计算代码块(函数)执行时间)
======================

**无参 computeTime(f)**

computeTime = code => {

let startTime = new Date().getTime();

code();

let endTime = new Date().getTime();

let time = endTime - startTime;

return time;

}

复制代码


**有参 computeTime(f)** 使用方法:computeTime(f,参数1,参数2......)

computeTime = f => {

let startTime = new Date().getTime();

let p = [];

for (let i = 1; i < arguments.length; i++) {

p.push(arguments[i])

}

f.apply(null, p)

let endTime = new Date().getTime();

let Time = endTime - startTime;

return Time;

}

复制代码


006.数字超过9显示省略号
==============

num_filter = val =>{

val = val?val-0:0;

if (val > 9 ) {

return "…"

}else{

return val;

}

}

复制代码


007.数字超过99显示99+
===============

ninenum_filter = val =>{

val = val?val-0:0;

if (val > 99 ) {

return "99+"

}else{

return val;

}

}

复制代码


008.银行卡号分割
==========

bank_filter = val =>{

val += ‘‘;

val = val.replace(/(\s)/g,‘‘).replace(/(\d{4})/g,‘$1 ‘).replace(/\s*$/,‘‘);

return val;

}

复制代码


009.防抖与节流
=========

/**

  • 函数防抖 (只执行最后一次点击)

    /

    Debounce = (fn, t) => {

    let delay = t || 500;

    let timer;

    return function () {

    let args = arguments;

    if(timer){

    clearTimeout(timer);

    }

    timer = setTimeout(() => {

    timer = null;

    fn.apply(this, args);

    }, delay);

    }

    };

    /

  • 函数节流

    */

    Throttle = (fn, t) => {

    let last;

    let timer;

    let interval = t || 500;

    return function () {

    let args = arguments;

    let now = +new Date();

    if (last && now - last < interval) {

    clearTimeout(timer);

    timer = setTimeout(() => {

    last = now;

    fn.apply(this, args);

    }, interval);

    } else {

    last = now;

    fn.apply(this, args);

    }

    }

    };

复制代码


010.深拷贝
=======

deepClone = source => {

const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象

for (let keys in source) { // 遍历目标

if (source.hasOwnProperty(keys)) {

if (source[keys] && typeof source[keys] === ‘object‘) { // 如果值是对象,就递归一下

targetObj[keys] = source[keys].constructor === Array ? [] : {};

targetObj[keys] = deepClone(source[keys]);

} else { // 如果不是,就直接赋值

targetObj[keys] = source[keys];

}

}

}

return targetObj;

}

let str1 = {

arr: [1, 2, 3],

obj: {

key: ‘value‘

},

fn: function () {

return 1;

}

};

let str3 = deepClone(str1);

console.log(str3 === str1); // false

console.log(str3.obj === str1.obj); // false

console.log(str3.fn === str1.fn); // true

复制代码


011.获取视口尺寸
==========

**需要在HTML文件中运行**

function getViewportOffset() {

if (window.innerWidth) {

return {

w: window.innerWidth,

h: window.innerHeight

}

} else {

// ie8及其以下

if (document.compatMode === "BackCompat") {

// 怪异模式

return {

w: document.body.clientWidth,

h: document.body.clientHeight

}

} else {

// 标准模式

return {

w: document.documentElement.clientWidth,

h: document.documentElement.clientHeight

}

}

}

}

复制代码


012.数字前补零
=========

/**

  • num为你想要进行填充的数字
  • length为你想要的数字长度

    */

//迭代方式实现

padding1=(num, length)=> {

for(let len = (num + "").length; len < length; len = num.length) {

num = "0" + num;

}

return num;

}

//递归方式实现

padding2=(num, length) =>{

if((num + "").length >= length) {

return num;

}

return padding2("0" + num, length)

}

//转为小数

padding3=(num, length)=> {

let decimal = num / Math.pow(10, length);

//toFixed指定保留几位小数

decimal = decimal.toFixed(length) + "";

return decimal.substr(decimal.indexOf(".")+1);

}

//填充截取法

padding4=(num, length)=> {

//这里用slice和substr均可

return (Array(length).join("0") + num).slice(-length);

}

//填充截取法

padding5=(num, length)=> {

let len = (num + "").length;

let diff = length+1 - len;

if(diff > 0) {

return Array(diff).join("0") + num;

}

return num;

}

复制代码


013.格式转换:base64转file
====================

/**

  • base64 base64
  • filename 转换后的文件名

    /

    base64ToFile = (base64, filename )=> {

    let arr = base64.split(‘,‘)

    let mime = arr[0].match(/难过.?);/)[1]

    let suffix = mime.split(‘/‘)[1] // 图片后缀

    let bstr = atob(arr[1])

    let n = bstr.length

    let u8arr = new Uint8Array(n)

    while (n--) {

    u8arr[n] = bstr.charCodeAt(n)

    }

    return new File([u8arr], ${filename}.${suffix}, { type: mime })

    }

    复制代码


014.格式转换:base64转blob
====================

base64ToBlob = base64 => {

let arr = base64.split(‘,‘),

mime = arr[0].match(/??.*?);/)[1],

bstr = atob(arr[1]),

n = bstr.length,

u8arr = new Uint8Array(n);

while (n--) {

u8arr[n] = bstr.charCodeAt(n);

}

return new Blob([u8arr], { type: mime });

};

复制代码


015.格式转换:blob转file
==================

blobToFile = (blob, fileName) => {

blob.lastModifiedDate = new Date();

blob.name = fileName;

return blob;

};

复制代码


016.格式转换:file转base64
====================

/**

  • file 图片文件
  • 返回图片的Base64数据

    */

    fileToBase64 = file => {

    let reader = new FileReader();

    reader.readAsDataURL(file);

    reader.onload = function (e) {

    return e.target.result

    };

    }

    复制代码


017.获取地址栏传递过来的参数
================

/**

  • name为地址栏传递过来的字段名

    /

    getQueryString = name => {

    let reg = new RegExp("(^|&)" + name + "=([^&])(&|$)");

    let r = window.location.search.substr(1).match(reg);

    if (r != null) return unescape(r[2]); return null;

    }

// 测试

// http://localhost:3306/admin?id=111&name=xxx

// console.log(getQueryString(‘id‘)); // 111

// console.log(getQueryString(‘name‘)); // xxx

复制代码


018.对象处理为数组对象
=============

/**

  • obj 需要处理的对象

    */

    objToArrObj = obj => {

    let arr = []

    for(let i in obj){

    arr.push({[i]:obj[i]})

    }

    return arr

    }

// 测试数据

let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}

console.log(objToArrObj(obj));

/*

[

{ 20180410: 5 },

{ 20180411: 13 },

{ 20180412: 26 },

{ 20180413: 16 }

]

*/

  

![手把手教你常用JS方法封装(一) [ 大杂烩 ]](http://p3.pstatp.com/large/dfic-imagehandler/a3548031-8354-4d74-a3c5-dd39f97e2390)

持续更新中...
========

常用JS方法封装方法预告:

*   项目常用JS方法封装(二) [ 时间处理 ]
*   项目常用JS方法封装(三) [ 字符串相关处理 ]
*   项目常用JS方法封装(四) [ 数组相关处理 ]

* * *

**使用方法非常简单,只需放到你的 utils.js 工具文件中,直接 export const 加上我的封装方法,在别的文件中使用{方法1,方法2,方法3...}引用后就可以直接使用了!**

001.输入一个值,返回其数据类型
=================

type = para => {

return Object.prototype.toString.call(para).slice(8,-1)

}

复制代码


002.阶乘
======

factorial = num => {

let count = 1;

for (let i = 1; i <= num; i++) {

count *= i;

}

return count;

}

复制代码


003.两个数之间累乘
===========

multBetride = (x, y) => {

let count;

if (x < y) {

count = x;

for (let i = x + 1; i <= y; i++) {

count *= i;

}

return count;

} else {

count = y;

for (let i = y + 1; i <= x; i++) {

count *= i;

}

return count;

}

}

复制代码


004.累加
======

()里面可以放N个实参

function cumsum() {

let sum = 0;

for (let i = 0; i < arguments.length; i++) {

sum += arguments[i];

}

return sum;

}

复制代码


005.计时器(计算代码块(函数)执行时间)
======================

**无参 computeTime(f)**

computeTime = code => {

let startTime = new Date().getTime();

code();

let endTime = new Date().getTime();

let time = endTime - startTime;

return time;

}

复制代码


**有参 computeTime(f)** 使用方法:computeTime(f,参数1,参数2......)

computeTime = f => {

let startTime = new Date().getTime();

let p = [];

for (let i = 1; i < arguments.length; i++) {

p.push(arguments[i])

}

f.apply(null, p)

let endTime = new Date().getTime();

let Time = endTime - startTime;

return Time;

}

复制代码


006.数字超过9显示省略号
==============

num_filter = val =>{

val = val?val-0:0;

if (val > 9 ) {

return "…"

}else{

return val;

}

}

复制代码


007.数字超过99显示99+
===============

ninenum_filter = val =>{

val = val?val-0:0;

if (val > 99 ) {

return "99+"

}else{

return val;

}

}

复制代码


008.银行卡号分割
==========

bank_filter = val =>{

val += ‘‘;

val = val.replace(/(\s)/g,‘‘).replace(/(\d{4})/g,‘$1 ‘).replace(/\s*$/,‘‘);

return val;

}

复制代码


009.防抖与节流
=========

/**

  • 函数防抖 (只执行最后一次点击)

    /

    Debounce = (fn, t) => {

    let delay = t || 500;

    let timer;

    return function () {

    let args = arguments;

    if(timer){

    clearTimeout(timer);

    }

    timer = setTimeout(() => {

    timer = null;

    fn.apply(this, args);

    }, delay);

    }

    };

    /

  • 函数节流

    */

    Throttle = (fn, t) => {

    let last;

    let timer;

    let interval = t || 500;

    return function () {

    let args = arguments;

    let now = +new Date();

    if (last && now - last < interval) {

    clearTimeout(timer);

    timer = setTimeout(() => {

    last = now;

    fn.apply(this, args);

    }, interval);

    } else {

    last = now;

    fn.apply(this, args);

    }

    }

    };

复制代码


010.深拷贝
=======

deepClone = source => {

const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象

for (let keys in source) { // 遍历目标

if (source.hasOwnProperty(keys)) {

if (source[keys] && typeof source[keys] === ‘object‘) { // 如果值是对象,就递归一下

targetObj[keys] = source[keys].constructor === Array ? [] : {};

targetObj[keys] = deepClone(source[keys]);

} else { // 如果不是,就直接赋值

targetObj[keys] = source[keys];

}

}

}

return targetObj;

}

let str1 = {

arr: [1, 2, 3],

obj: {

key: ‘value‘

},

fn: function () {

return 1;

}

};

let str3 = deepClone(str1);

console.log(str3 === str1); // false

console.log(str3.obj === str1.obj); // false

console.log(str3.fn === str1.fn); // true

复制代码


011.获取视口尺寸
==========

**需要在HTML文件中运行**

function getViewportOffset() {

if (window.innerWidth) {

return {

w: window.innerWidth,

h: window.innerHeight

}

} else {

// ie8及其以下

if (document.compatMode === "BackCompat") {

// 怪异模式

return {

w: document.body.clientWidth,

h: document.body.clientHeight

}

} else {

// 标准模式

return {

w: document.documentElement.clientWidth,

h: document.documentElement.clientHeight

}

}

}

}

复制代码


012.数字前补零
=========

/**

  • num为你想要进行填充的数字
  • length为你想要的数字长度

    */

//迭代方式实现

padding1=(num, length)=> {

for(let len = (num + "").length; len < length; len = num.length) {

num = "0" + num;

}

return num;

}

//递归方式实现

padding2=(num, length) =>{

if((num + "").length >= length) {

return num;

}

return padding2("0" + num, length)

}

//转为小数

padding3=(num, length)=> {

let decimal = num / Math.pow(10, length);

//toFixed指定保留几位小数

decimal = decimal.toFixed(length) + "";

return decimal.substr(decimal.indexOf(".")+1);

}

//填充截取法

padding4=(num, length)=> {

//这里用slice和substr均可

return (Array(length).join("0") + num).slice(-length);

}

//填充截取法

padding5=(num, length)=> {

let len = (num + "").length;

let diff = length+1 - len;

if(diff > 0) {

return Array(diff).join("0") + num;

}

return num;

}

复制代码


013.格式转换:base64转file
====================

/**

  • base64 base64
  • filename 转换后的文件名

    /

    base64ToFile = (base64, filename )=> {

    let arr = base64.split(‘,‘)

    let mime = arr[0].match(/难过.?);/)[1]

    let suffix = mime.split(‘/‘)[1] // 图片后缀

    let bstr = atob(arr[1])

    let n = bstr.length

    let u8arr = new Uint8Array(n)

    while (n--) {

    u8arr[n] = bstr.charCodeAt(n)

    }

    return new File([u8arr], ${filename}.${suffix}, { type: mime })

    }

    复制代码


014.格式转换:base64转blob
====================

base64ToBlob = base64 => {

let arr = base64.split(‘,‘),

mime = arr[0].match(/??.*?);/)[1],

bstr = atob(arr[1]),

n = bstr.length,

u8arr = new Uint8Array(n);

while (n--) {

u8arr[n] = bstr.charCodeAt(n);

}

return new Blob([u8arr], { type: mime });

};

复制代码


015.格式转换:blob转file
==================

blobToFile = (blob, fileName) => {

blob.lastModifiedDate = new Date();

blob.name = fileName;

return blob;

};

复制代码


016.格式转换:file转base64
====================

/**

  • file 图片文件
  • 返回图片的Base64数据

    */

    fileToBase64 = file => {

    let reader = new FileReader();

    reader.readAsDataURL(file);

    reader.onload = function (e) {

    return e.target.result

    };

    }

    复制代码


017.获取地址栏传递过来的参数
================

/**

  • name为地址栏传递过来的字段名

    /

    getQueryString = name => {

    let reg = new RegExp("(^|&)" + name + "=([^&])(&|$)");

    let r = window.location.search.substr(1).match(reg);

    if (r != null) return unescape(r[2]); return null;

    }

// 测试

// http://localhost:3306/admin?id=111&name=xxx

// console.log(getQueryString(‘id‘)); // 111

// console.log(getQueryString(‘name‘)); // xxx

复制代码


018.对象处理为数组对象
=============

/**

  • obj 需要处理的对象

    */

    objToArrObj = obj => {

    let arr = []

    for(let i in obj){

    arr.push({[i]:obj[i]})

    }

    return arr

    }

// 测试数据

let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}

console.log(objToArrObj(obj));

/*

[

{ 20180410: 5 },

{ 20180411: 13 },

{ 20180412: 26 },

{ 20180413: 16 }

]

*/

原文地址:https://www.cnblogs.com/lihanlin/p/12571875.html

时间: 2024-10-18 01:28:26

step by step教你常用JS方法封装(一) [ 大杂烩 ]的相关文章

常用js方法封装

常用js方法封装 var myJs = { /* * 格式化日期 * @param dt 日期对象 * @returns {string} 返回值是格式化的字符串日期 */ getDates: function(dt) { var str = ""; //存储时间的字符串 //获取年 var year = dt.getFullYear(); //获取月 var month = dt.getMonth() + 1; //获取日 var day = dt.getDate(); //获取小时

常用js方法封装使用

// 冒泡排序 export function bubbleSort(arr) { let i = arr.length - 1; while (i > 0) { let maxIndex = 0; for (let j = 0; j < i; j++) { if (arr[j] > arr[j + 1]) { let temp = arr[j + 1]; arr[j + 1] = arr[j]; arr[j] = temp; maxIndex = j; } } i = maxIndex

常用js方法整理common.js

项目中常用js方法整理成了common.js var h = {}; h.get = function (url, data, ok, error) { $.ajax({ url: url, data: data, dataType: 'json', success: ok, error: error }); } h.post = function (url, data, ok, error) { $.ajax({ url: url, data: data, type: 'post', data

常用JS方法

// 悬浮置顶 ; (function ($) { $.fn.crumbsFixedPosition = function (options) { var defaults = { cName: 'fixed_pos' } var options = $.extend(defaults, options); return this.each(function () { var $this = $(this); var t = $(this).offset().top; $(window).on(

javascript中最最最常用的方法封装

javascript 常用方法的封装,小编持续升级中... 方法封装(js原生): 一.Object 类型 MHQ.ajaxUtils 定义一个ajax工具类 ajax 定义一个ajax工具函数 get 方法 post 方法 MHQ.elementUtils DOM元素工具类 replaceClassName 替换字符串,设置className属性 getInnerText 获取DOM元素内部文本的兼容方法 setInnerText 设置DOM元素内部文本的兼容方法 getNextElement

常用JS方法整理

本篇目录: 1.截取指定字节数的字符串 2.判断是否微信 3.获取时间格式的几个举例 4.获取字符串字节长度 5.对象克隆.深拷贝 6.组织结构代码证验证 7.身份证号验证 8.js正则为url添加http标识 9.URL有效性校验方法 10.自定义jsonp方法 11.cookie操作 12.生成随机字符串 (可指定长度) 13.浏览器判断 14.Rem移动端适配 15.获取url后参数 16.动态加载JS 17.生成随机颜色值 上述方法都是日常工作中使用所得,所以会不定时更新,大家也可以留下

在项目中常用的JS方法封装

使用方法简单,只需要放在你的 utils.js 工具文件中,直接export const 加上下面封装方法,在别的文件中使用 {方法1,方法2,方法3...}引用后直接使用即可. 01.输入一个值.返回其数据类型 type = para =>{ return Object.toString.call(para).slice(8,-1) } 02.冒泡排序 升序 bubbleAsSort() bubbleAsSort = arr =>{ for(let i=0;i<arr.length -

简单封装常用js方法

1.uploadfiy插件封装 /* 参数:uploadID:上传控件ID url:请求后台url路径   callback:回调函数 */ uploadfiy({ uploadID: $('#btn_upload'), url: '/sys/upload', callback: function (data) { if (data.success) { //todo:do something.... } } }); function uploadfiy(options) { var setti

项目中常用js方法整理common.js

var h = {}; h.get = function (url, data, ok, error) { $.ajax({ url: url, data: data, dataType: 'json', success: ok, error: error }); } h.post = function (url, data, ok, error) { $.ajax({ url: url, data: data, type: 'post', dataType: 'json', success: