码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2020-03-26 09:14:18      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:match   interval   add   mod   substr   call   factor   prototype   格式   

本文参考原文-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 }
]
*/

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

标签:match   interval   add   mod   substr   call   factor   prototype   格式   

原文地址:https://www.cnblogs.com/lihanlin/p/12571875.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!