# JS收藏夹

# 文章

# 函数参数校验器

const isRequired = () => {
    throw new Error('param is required');
};

function(name = isRequired()) {
    console.log(name)
};
print('husky'); // husky
print(); // 报错
print(null); // null
1
2
3
4
5
6
7
8
9
10

# 校验是否为JSON字符串

export function isJsonString(str) {
    try {
        if (typeof JSON.parse(str) === 'object') {
            return true
        }
    } catch (e) {
        return false
    }
}
1
2
3
4
5
6
7
8
9

# 利用JSON.stringify去除多余的属性

  • 假定我们只需要传给后台name和id属性,可是要传递的对象多了很多属性
let params = {
    name: '🐰哈哈',
    id: 1,
    type: 'husky',
    shortName: '2ha',
    englishName: 'twohaha'
}
params = JSON.parse(JSON.stringify(params, ['id', 'name']))
console.log(params)
// {id: 1, name: "twohaha"}
1
2
3
4
5
6
7
8
9
10

# 清除全部cookie

export function clearCookie() {
    // 通过正则匹配到全部的cookie的key
    const cookieArr = document.cookie.match(/[^ =;]+(?==)/g)
    if (cookieArr && Object.prototype.toString.call(cookieArr) === '[object Array]') {
        cookieArr.forEach(item => {
            Cookies.remove(item) // 开始清除
        })
    }
}
1
2
3
4
5
6
7
8
9

# 合并多个对象

/**
 * @param {Object} multiple object
 * @return {Object}  merge object
 */
export function merge(target) {
    for (let i = 1, j = arguments.length; i < j; i++) {
        const source = arguments[i] || {};
        for (const prop in source) {
            if (source.hasOwnProperty(prop)) {
                const value = source[prop];
                if (value !== undefined) {
                    target[prop] = value;
                }
            }
        }
    }

    return target;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 判断元素是否包含在容器中

export const isInContainer = (el, container) => {
    const elRect = el.getBoundingClientRect()
    let containerRect

    if ([window, document, document.documentElement, null, undefined].includes(container)) {
        containerRect = {
            top: 0,
            right: window.innerWidth,
            bottom: window.innerHeight,
            left: 0
        };
    } else {
        containerRect = container.getBoundingClientRect()
    }

    return elRect.top < containerRect.bottom &&
        elRect.bottom > containerRect.top &&
        elRect.right > containerRect.left &&
        elRect.left < containerRect.right
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 封装addEventListener

export const on = (function() {
    if (document.addEventListener) {
        return function(element, event, handler) {
            if (element && event && handler) {
                element.addEventListener(event, handler, false);
            }
        };
    } else {
        return function(element, event, handler) {
            if (element && event && handler) {
                element.attachEvent('on' + event, handler);
            }
        };
    }
})();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 封装removeEventListener

export const off = (function() {
    if (document.removeEventListener) {
        return function(element, event, handler) {
            if (element && event) {
                element.removeEventListener(event, handler, false);
            }
        };
    } else {
        return function(element, event, handler) {
            if (element && event) {
                element.detachEvent('on' + event, handler);
            }
        };
    }
})();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 封装一次绑定方法once

  • offon 用到了上面封装的方法
export const once = function(el, event, fn) {
    var listener = function() {
        if (fn) {
            fn.apply(this, arguments);
        }
        off(el, event, listener);
    };
    on(el, event, listener);
};
1
2
3
4
5
6
7
8
9

# 获取密码输入框内容

  • 方法一
document.querySelector('input[type=password]').value
1
  • 方法二
document.querySelector('input[type=password]').setAttribute('type', 'text')
1

# 模板字符串应用一

  • 配合对象解构赋值效果更佳
function details({
    name,
    address,
    phone
}) {
    return `name:${name}, address:${address}, phone:${phone}`
}
1
2
3
4
5
6
7

# 模板字符串应用二

  • 作为函数实参





 



function huskyDetails (content, weight) {
  let bodyType = weight > 20 ? 'big' : 'small'
  return `${content[0]} is ${bodyType} dog`
}

huskyDetails `husky${25}`
// husky is big dog

1
2
3
4
5
6
7
8

# 根据数字返回星期

function backDate( number ) {
  return number <= 7? `星期${'日一二三四五六日'.charAt(number)}` :''
}
1
2
3

# 判断元素是否有滚动条

# 判断竖向是否有滚动条

  element.scrollHeight > element.clientHeight;
1

# 判断横向是否有滚动条

  element.scrollWidth > element.clientWidth;
1

# 计算默认滚动条的宽度

// 计算滚动条宽度的方法:新建一个带有滚动条的DIV元素,再计算该元素offsetWidth和clientWidth的差值。
function getScrollbarWidth() {

    var scrollDiv = document.createElement("div");
    scrollDiv.style.cssText = 'width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;';
    document.body.appendChild(scrollDiv);
    var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
    document.body.removeChild(scrollDiv);

    return scrollbarWidth;
};
1
2
3
4
5
6
7
8
9
10
11

# 检测平台

### 判断IOS系统

((navigator.userAgent.toLowerCase().indexOf('iphone') !== -1 ||
        navigator.userAgent.toLowerCase().indexOf('ipod') !== -1 ||
        navigator.userAgent.toLowerCase().indexOf('ipad') !== -1 ||
        navigator.userAgent.toLowerCase().indexOf('mobile') !== -1 ||
        navigator.userAgent.toLowerCase().indexOf('android') !== -1) ?
    true : false)
1
2
3
4
5
6

# 判断IE系统

((navigator.userAgent.toLowerCase().indexOf('msie') !== -1 ||
        navigator.userAgent.toLowerCase().indexOf('trident') !== -1) ?
    true : false)
1
2
3

# 退出进入全屏

# 进入全屏

// params 可以传入想要全屏的元素
function requestFullScreen(element) {
    // 判断各种浏览器,找到正确的方法
    var requestMethod = element.requestFullScreen || //W3C
        element.webkitRequestFullScreen || //FireFox
        element.mozRequestFullScreen || //Chrome等
        element.msRequestFullScreen; //IE11
    if (requestMethod) {
        requestMethod.call(element);
    } else if (typeof window.ActiveXObject !== "undefined") { //for Internet Explorer
        var wscript = new ActiveXObject("WScript.Shell");
        if (wscript !== null) {
            wscript.SendKeys("{F11}");
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 退出全屏

function exitFull() {
    // 判断各种浏览器,找到正确的方法
    var exitMethod = document.exitFullscreen || //W3C
        document.mozCancelFullScreen || //FireFox
        document.webkitExitFullscreen || //Chrome等
        document.webkitExitFullscreen; //IE11
    if (exitMethod) {
        exitMethod.call(document);
    } else if (typeof window.ActiveXObject !== "undefined") { //for Internet Explorer
        var wscript = new ActiveXObject("WScript.Shell");
        if (wscript !== null) {
            wscript.SendKeys("{F11}");
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 不常用技巧

# Node突破内存限制

# 方式一

  • 直接在终端运行下面这段代码即可,也可持久化到package.json的script中
export NODE_OPTIONS='--max-old-space-size=4096'
1

# 方式二

node --max-old-space-size=8192 [file].js 
1
  • 内存的大小可以设置为 [2048, 4096, 8192, 16384] 等等

# new Function 的方式创建异步方法

const AsyncFunction = Object.getPrototypeOf(async function() {}).constructor;

const fetchPage = new AsyncFunction("url", "return await fetch(url); ");

fetchPage('./index.json').then((res) => {

    return res.json();

}).then((res) => {

    console.log(res);

})
1
2
3
4
5
6
7
8
9
10
11
12
13
Last Updated: 1/23/2022, 10:16:22 AM