search
HomeWeb Front-endJS Tutorial10 common js functions

10 common js functions

Feb 22, 2018 pm 02:02 PM
javascriptCommonly used

1,对于cookie的操作,其中包括了设置、获取、删除cookie的操作。下面这个是我在公司的项目里面使用的工具库里的方法,测试就不测试了

// setCookie()// @About 设置cookiefunction setCookie(name, value) {    var Days = 30;    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}// getCookie()// @About 获取cookiefunction getCookie(name) {    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));    if (arr != null) {        return (arr[2]);
    } else {        return "";
    }
}// delCookie()// @About 删除cookiefunction delCookie(name) {    var exp = new Date();
    exp.setTime(exp.getTime() - 1);    var cval = getCookie(name);    if (cval != null) {      document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
    }
}

2,随机返回一个范围的数字。参数是两个的时候,返回传入的两个参数的区间的随机函数;参数是一个的时候,返回0到这个数的随机函数;参数是零个的时候,返回0到255区间的整数,大家可以根据自己的需要进行扩展

function randomNumber(n1,n2){    if(arguments.length===2){        return Math.round(n1+Math.random()*(n2-n1));
    }    
    else if(arguments.length===1){        return Math.round(Math.random()*n1)
    }    //    //    else{        return Math.round(Math.random()*255)
    }  
}

randomNumber(5,10) // 返回5-10的随机整数,包括5,10randomNumber(10)   // 返回0-10的随机整数,包括0,10randomNumber()     // 返回0-255的随机整数,包括0,255

3,到某一个时间的倒计时,传入的参数以 (YYYY/MM/DD H:mm:ss)

function getEndTime(endTime){    var startDate=new Date();  //开始时间,当前时间    var endDate=new Date(endTime); //结束时间,需传入时间参数    var t=endDate.getTime()-startDate.getTime();  //时间差的毫秒数    var d=0,h=0,m=0,s=0;    if(t>=0){
      d=Math.floor(t/1000/3600/24);
      h=Math.floor(t/1000/60/60%24);
      m=Math.floor(t/1000/60%60);
      s=Math.floor(t/1000%60);
    } 
    return "剩余时间"+d+"天 "+h+"小时 "+m+" 分钟"+s+" 秒";
}

getEndTime('2018/8/8 8:0:0') // "剩余时间172天 12小时 10 分钟47 秒"

4,清除对象中值为空的属性

function filterParams(obj){    let _newPar = {};    for (let key in obj) {        if ((obj[key] !== 0 && obj[key]) && obj[key].toString().replace(/(^\s*)|(\s*$)/g, '') !== '') {
            _newPar[key] = obj[key];
        }
    }    return _newPar;
}

filterParams({a:0, b:1, c:"010", d:null, e:undefined,f:false}) 
// 当值等于0,null,undefined的时候,就会被过滤

这里涉及到了一个知识点:&&和||运算符的先后顺序,我相信大部分的朋友都知道,我就简单提一下:

  • return  a && b || c ,
    根据a来判断返回值,a 是 false 则肯定返回 c;如果 b , c 都是 true ,那么我们就可以根据 a 来决定b 还是 c ,如果 a 是 false 则返回 c,如果a是true 则返回 b。

    var a = 3  &&  0 || 2;  //2
  • return a || b && c

    根据优先级相当于先算 b && c ,然后和a 相 或;如果a是true,则返回a,不论是b或c,如果a是false,则如果b是false,返回b,如果b是true,返回c;

    var b = 3 || 0  &&  2; // 3var c= 0 || 2 && 3; // 3

更多操作大家可以参考JS运算符&&和|| 及其优先级


5,获取,设置url参数,url 参数就是其中 ? 后面的参数

function getUrlPrmt(url) {
    url = url ? url : window.location.href;    let _pa = url.substring(url.indexOf(&#39;?&#39;) + 1), _arrS = _pa.split(&#39;&&#39;), _rs = {};    for (let i = 0, _len = _arrS.length; i < _len; i++) {        let pos = _arrS[i].indexOf(&#39;=&#39;);        if (pos == -1) {            continue;
        }        let name = _arrS[i].substring(0, pos), value = window.decodeURIComponent(_arrS[i].substring(pos + 1));
        _rs[name] = value;
    }    return _rs;
}

结果如下:

10 common js functions
10 common js functions
demo_5.png

这里是设置url参数的函数,如果对象中有nullundefined,则会自动过滤。

function setUrlPrmt(obj) {    let _rs = [];    for (let p in obj) {        if (obj[p] != null && obj[p] != '') {
            _rs.push(p + '=' + obj[p])
        }
    }    return _rs.join('&');
}

setUrlPrmt({a:'0', b:1, c:"010", d:null, e:undefined,f:false}) // "a=0&b=1&c=010"

6,获取文件后缀名的方法,参数的file_name,即传进来的文件;返回值是扩展名、后缀名的位置下标以及文件名

function getSuffix(file_name) {    var result = /[^\.]+$/.exec(file_name);    return result;
}

getSuffix('1234.png') // ["png", index: 5, input: "1234.png"]getSuffix('1231344.file'); // ["file", index: 8, input: "1231344.file"]

7,查看浏览器是否支持某一个css3的属性,不如firefox浏览器中是不支持-webkit-开头的属性的

function supportCss3(style) {    var prefix = ['webkit', 'Moz', 'ms', 'o'],
        i,
        humpString = [],
        htmlStyle = document.documentElement.style,
        _toHumb = function(string) {            return string.replace(/-(\w)/g, function($0, $1) {                return $1.toUpperCase();
            });
        };    for (i in prefix)
        humpString.push(_toHumb(prefix[i] + '-' + style));
    humpString.push(_toHumb(style));    for (i in humpString)        if (humpString[i] in htmlStyle) return true;    return false;
}
这个是chorme中的结果:
10 common js functions
10 common js functions
chorme1.png

这个是firefox中的结果:

10 common js functions
10 common js functions
firefox.png

8,怎么判断一个对象是不是数组类型?

我们采取最常用的方法:根据对象的class属性(类属性),跨原型链调用toString()方法。

function _getClass(o){    return Object.prototype.toString.call(o).slice(8,-1);
}

_getClass(new Date()); // Date_getClass(&#39;maolei&#39;);   // String

此外如果你想要了解更多的判断是不是数组类型的方法,可参考:判断一个对象是不是数组类型


9,js的排序算法,这里就使用最简单的冒泡排序,关于js的选择排序算法,大家可以参考js十大排序算法详解

function bubbleSort(arr) {    var len = arr.length;    for (var i = 0; i < len; i++) {        for (var j = 0; j < len - 1 - i; j++) {            if (arr[j] > arr[j+1]) {        //相邻元素两两对比                var temp = arr[j+1];        //元素交换
                arr[j+1] = arr[j];
                arr[j] = temp;
            }
        }
    }    return arr;
}var arr=[3,44,38,5,47,15,36,26,27,2,46,4,19,50,48];
bubbleSort(arr);//[2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50] ;

render(&#39;我是{{name}},年龄{{age}},性别{{sex}}&#39;,{
    name:&#39;姓名&#39;,
    age:18,
    sex:&#39;女&#39;})

我们可以用正则表达式和replace解决:

var render = function(tpl,data){    return tpl.replace(/\{\{(.+?)\}\}/g,function(m,m1){        return data[m1]
    })
}

render(&#39;我是{{name}},年龄{{age}},性别{{sex}}&#39;,{    name:&#39;姓名&#39;,    age:18,sex:&#39;女&#39;,
}) 
// "我是姓名,年龄18,性别女"

相关推荐:

180多个PHP常用函数总结

MySQL中的常用函数详解

php正则表达式中常用函数的详解

The above is the detailed content of 10 common js functions. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor