js常用代码段总结

这篇文章旨在整理总结前端开发过程中经常遇到的代码段

持续更新
1.对象,数组的深拷贝

注:支持1:数组深拷贝,2:对象深拷贝,3:嵌套数组的数组深拷贝,4:嵌套对象的对象深拷贝,5:嵌套对象的数组深拷贝, 6:嵌套数组的对象深拷贝

const objDeepCopy = (source) => {
    const sourceCopy = source instanceof Array ? [] : {};
    Object.keys(source).forEach((key) => {
        sourceCopy[key] = typeof source[key] === 'object' ? objDeepCopy(source[key]) : source[key];
    });
    return sourceCopy;
};
/* 数组深拷贝 */
let a = [1,2,3];
let b = a;
let c = objDeepCopy(a);
a[2]=33;
console.log('a', a);   /* [1,2,33]*/
console.log('b', b);   /* [1,2,33]*/
console.log('c', c);   /* [1,2,3]*/

/* 对象深拷贝 */
let a = {key1: 1, key2: 2, key3: 3};
let b = a;
let c = objDeepCopy(a);
a.key3=33;
console.log('a', a);   /* {key1: 1, key2: 2, key3: 33}*/
console.log('b', b);   /* {key1: 1, key2: 2, key3: 33}*/
console.log('c', c);   /* {key1: 1, key2: 2, key3: 3}*/
2.获取url上的参数

注:url上没有该参数时返回undefined


    
        
    

3:给url添加参数
const setParameter = (url, parameters) => {
    if (Object.keys(parameters).length === 0) {
        return url;
    }
    let newUrl = url;
    Object.keys(parameters).forEach((key) => {
        const value = parameters[key];
        if (newUrl.indexOf('?') >= 0) {
            newUrl += `&${key}=${value}`;
        } else {
            newUrl += `?${key}=${value}`;
        }
    });
    return newUrl;
}
const url = 'http://cctv.com';
const url2 = 'http://cctv.com?origin=10';
console.log(setParameter(url,{a:3}));   /* http://cctv.com?a=3 */
console.log(setParameter(url,{a:3, b:4}));  /* http://cctv.com?a=3&b=4 */
console.log(setParameter(url2,{a:3}));    /* http://cctv.com?origin=10&a=3 */
console.log(setParameter(url2,{a:3, b:4}));  /* http://cctv.com?origin=10&a=3&b=4 */

4.将一个Date类型的对象转化为“yyyy-mm-dd”

注:月和日,若小于10,前面补0位

const formatDate = (date) => {
    let monthDigital = date.getMonth()+1;
    if (monthDigital < 10) {
        monthDigital = `0${monthDigital}`;
    }
    let dateDigital = date.getDate();
    if (dateDigital < 10) {
        dateDigital = `0${dateDigital}`;
    }
    return `${date.getFullYear()}-${monthDigital}-${dateDigital}`;
};
var today = new Date();  /* 2017-10-21*/
console.log(formatDate(today));

var date = new Date();  
date.setDate(date.getDate()-18);
console.log(formatDate(date)); /* 2017-10-03*/

5:将带有length参数的对象转成数组(jquery获取到的dom对象使用)
注:
1:该对象必须有length参数(可以自己添加)
2:该对象的key必须是1,2,3....
3:非常适用处理“通过jquery获取到dom时得到的对象”

const getListFromObject = (argument) => {
    Array.prototype.slice.call(argument);
    return Array.prototype.slice.call(argument);
}
const argument = {
      length: 2,
      0: 'data1',
      1: 'data2'
}
getListFromObject(argument);
console.log(argument);    /* { '0': 'data1', '1': 'data2', length: 2 } */
console.log(getListFromObject(argument));   /* [ 'data1', 'data2' ]*/

6:用纯原生js通过class绑定方法


    
        
    
    

7.对象数组,根据某key排序

const sortByStatus = (list, orderParameter, orderStatus) => {
    var compare = function (property){
        return function(a,b){
            var value1 = a[property];
            var value2 = b[property];
            let orderBase = value1 - value2;
            if (orderStatus === 'desc') {
                orderBase *= -1;
            }
            return orderBase;
        }
    };
    list.sort(compare(orderParameter));
    return list;
}
const list = [{index: 1, a:3, b:4, c:5}, {index: 2, a:1, b:9, c:10}, {index: 3, a:2, b:5, c:9}];
console.log(sortByStatus(list, 'a', 'asc'));  
/*
[ { index: 2, a: 1, b: 9, c: 10 },
  { index: 3, a: 2, b: 5, c: 9 },
  { index: 1, a: 3, b: 4, c: 5 } ]
*/
console.log(sortByStatus(list, 'a', 'desc'));
/*
[ { index: 1, a: 3, b: 4, c: 5 },
  { index: 3, a: 2, b: 5, c: 9 },
  { index: 2, a: 1, b: 9, c: 10 } ]
*/

你可能感兴趣的:(js常用代码段总结)