常用的JS方法

蒋子宁
• 阅读 977

一,判断当前元素是否是数组

1,通过 constructor 判断

function isArray(value) {
    return value && typeof value == 'object' && value.constructor === Array
}

2,通过 instanceof 判断判断

function isArray(value) {
    return value && typeof value == 'object' && value instanceof Array
}

3,通过 toString 判断

function isArray(value) {
    return Array.isArray(value) || (typeof value == 'object' && Object.prototype.toString.call(value) === '[object Array]')
}

4,isArray 原生方法判断

Array.isArray()

二,判断是否是对象

function isObject(value) {
    return value != null && typeof value === 'object' && Object.prototype.toString.call(value) === '[object Object]'
}

三,判断环境

1,判断是否安卓

function isAndroid() {
    return /Android/i.test(navigator.userAgent) || /Linux/i.test(navigator.appVersion);
}

2,判断是否ios

function isIOS() {
    return (/ipad|iphone/i.test(navigator.userAgent));
}

3,判断是否是Safari

function isSafari() {
    return (/msie|applewebkit.+safari/i.test(navigator.userAgent));
}

4,判断是否在微信

function isWeixin() {
    return /MicroMessenger/i.test(navigator.userAgent);
}

5,判断是否为移动端

function isMobile() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobi/i.test(navigator.userAgent) ||
        screen.width < 500;
}

四,按需加载CSS与JS

/**
 * 按需加载js
 * @param {*} path
 */
function delayLoadJS(path) {
    if (!path) {
        return Promise.reject();
    }
    return new Promise((resolve, reject) => {
        let dom = null;
        const scripts = document.querySelectorAll('script');
        for (let item of scripts) {
            if (new RegExp(path).test(item.src)) {
                dom = item;
                onload(dom, () => resolve());
                return;
            }
        }
        if (!dom) {
            const script = document.createElement('script');
            script.src = path;
            script.onload = () => {
                resolve();
                script.onload = null;
            };
            script.onerror = () => reject();
            document.body.appendChild(script);
        }
    });
}
/**
 * 按需加载css
 * @param {*} path
 */
function delayLoadCSS(path) {
    if (!path) {
        return Promise.reject();
    }
    return new Promise((resolve, reject) => {
        let dom = null;
        let links = document.querySelectorAll('link');
        for (let item of links) {
            if (new RegExp(path).test(item.href)) {
                dom = item;
                onload(dom, resolve);
                return;
            }
        }
        if (!dom) {
            const link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = path;
            link.onload = () => {
                resolve();
                link.onload = null;
            };
            link.onerror = () => reject();
            document.head.appendChild(link);
        }
    });
}
/**
 * 解决同时异步加载同一个文件的问题
 * @param {*} dom
 * @param {*} resolve
 */
function onload(dom, resolve) {
    const oldOnload = dom.onload;
    if (oldOnload) {
        dom.onload = () => {
            oldOnload();
            resolve();
        };
    } else {
        resolve();
    }
}

五,常用正则表达式

1,邮箱

function isEmail(email) {
    var r = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return r.test(email);
}

2,QQ

function isQQ(qq) {
    var r = /^[1-9]\d{4,10}$/;
    return r.test(qq);
}

3,网址

function isUrl(str) {
    return /^(((ht)tps?):\/\/)?[\w\-]+(\.[\w\-]+)+([\w\-.,@?^=%&:\/~+#]*[\w\-@?^=%&\/~+#])?$/.test(str);
}

4,身份证

function isCard(str) {
    return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
}

5,汉字

function isChinese(str) {
    return /^[\u4e00-\u9fa5]+$/.test(str);
}

6,英文

function isEnglish(str) {
    return /^[a-zA-Z]*$/.test(str);
}

六,对象的深拷贝

1,对象

// 简单粗暴,一步到位
JSON.parse(JSON.stringify(obj));

2,数组

可以用Array.slice(),Array.concat(),ES6扩展运算符...等方法来实现

七,结语

以上大概是目前来说项目中运用较多的一些公用方法,可能实现方法不是最好的,这里仅供参考。还有许多通用的方法,这里只想起这么多了,以后再慢慢补充吧。

作者:易企秀——易小星
点赞
收藏
评论区
推荐文章
blmius blmius
4年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
待兔 待兔
1年前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Wesley13 Wesley13
4年前
java中比较两个时间的差值
项目背景1.某篇文稿的发布时间是publishDate,例如:2020072118:00:41。2.现要求判断该篇文稿的发布时间是否在近30天之内。publicstaticlongdayDiff(DatecurrentDate,DatepublishDate){LongcurrentTimecurrentDat
Stella981 Stella981
4年前
ClickHouse在字节跳动广告DMP&CDP的应用
展开function\_typeof(e){returne&amp;&amp;"undefined"!typeofSymbol&amp;&amp;e.constructorSymbol?"symbol":typeofe;}!function(e){if("object"("undefined"typeofmodule?
Stella981 Stella981
4年前
JavaScript中判断数组是否包含某个元素
javascript的Array没有contains方法,有时候这会不方便,contains方法实现很简单可以扩展Array类,如下:写法1.Array.prototype.containsfunction(obj){varithis.length;while(i){
Stella981 Stella981
4年前
Flutter中动态显示组件之“坑”,我来教你怎样爬上来
展开function\_typeof(e){returne&amp;&amp;"undefined"!typeofSymbol&amp;&amp;e.constructorSymbol?"symbol":typeofe;}!function(e){if("object"("undefined"typeofmodule?
Stella981 Stella981
4年前
Python怎样查询MySQL数据库?
ShowMorefunction\_typeof(e){returne&amp;&amp;"undefined"!typeofSymbol&amp;&amp;e.constructorSymbol?"symbol":typeofe;}!function(e){if("object"("undefined"typeof
Wesley13 Wesley13
4年前
PHP高性能编程
1.能用PHP数组完成的工作,绝不用文件形式来代替,数组是内存操作,内存操作速度对比文件操作快很多!2.判断一个数值是否在一个数组中,然后决定是否追加数组内容时,不推荐使用in\_array或者array\_key\_exists,因为函数判断都不如isset结构判断来的快!$num0;$resultar
Stella981 Stella981
4年前
SeleniumConf
展开function\_typeof(e){returne&amp;&amp;"undefined"!typeofSymbol&amp;&amp;e.constructorSymbol?"symbol":typeofe;}!function(e){if("object"("undefined"typeofmodule?
Stella981 Stella981
4年前
Python竟然能画这么漂亮的折线图运营妹子看到直接哭了
ShowMorefunction\_typeof(e){returne&amp;&amp;"undefined"!typeofSymbol&amp;&amp;e.constructorSymbol?"symbol":typeofe;}!function(e){if("object"("undefined"typeof
达里尔 达里尔
2年前
给数组添加新数据,判断数据是否重复
多选要进行数组拼接,希望判断往原数组里添的新数据是否重复,封装个简易方法languageconstdataArrayname:'aaa',id:1,name:'bbb',id:2;constnewDataname:'ccc',id:2;//要添加的新数