Table of Contents
2,随机返回一个范围的数字。参数是两个的时候,返回传入的两个参数的区间的随机函数;参数是一个的时候,返回0到这个数的随机函数;参数是零个的时候,返回0到255区间的整数,大家可以根据自己的需要进行扩展
3,到某一个时间的倒计时,传入的参数以 (YYYY/MM/DD H:mm:ss)
4,清除对象中值为空的属性
5,获取,设置url参数,url 参数就是其中 ? 后面的参数
6,获取文件后缀名的方法,参数的file_name,即传进来的文件;返回值是扩展名、后缀名的位置下标以及文件名
7,查看浏览器是否支持某一个css3的属性,不如firefox浏览器中是不支持-webkit-开头的属性的
8,怎么判断一个对象是不是数组类型?
js十大排序算法详解" >9,js的排序算法,这里就使用最简单的冒泡排序,关于js的选择排序算法,大家可以参考js十大排序算法详解
前端笔试题十讲中听到的一个题目:实现一个最简单的模板引擎,感觉很有趣,就直接以这道题作为结尾吧" >10,最后是我在一个前端大神芋头君live前端笔试题十讲中听到的一个题目:实现一个最简单的模板引擎,感觉很有趣,就直接以这道题作为结尾吧
Home Web Front-end JS Tutorial 10 common js functions

10 common js functions

Feb 22, 2018 pm 02:02 PM
javascript Commonly 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();
    }
}
Copy after login

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
Copy after login

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 秒"
Copy after login

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的时候,就会被过滤
Copy after login

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

  • 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
    Copy after login
  • 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
    Copy after login

更多操作大家可以参考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;
}
Copy after login

结果如下:

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] != &#39;&#39;) {
            _rs.push(p + &#39;=&#39; + obj[p])
        }
    }    return _rs.join(&#39;&&#39;);
}

setUrlPrmt({a:&#39;0&#39;, b:1, c:"010", d:null, e:undefined,f:false}) // "a=0&b=1&c=010"
Copy after login

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

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

getSuffix(&#39;1234.png&#39;) // ["png", index: 5, input: "1234.png"]getSuffix(&#39;1231344.file&#39;); // ["file", index: 8, input: "1231344.file"]
Copy after login

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

function supportCss3(style) {    var prefix = [&#39;webkit&#39;, &#39;Moz&#39;, &#39;ms&#39;, &#39;o&#39;],
        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] + &#39;-&#39; + style));
    humpString.push(_toHumb(style));    for (i in humpString)        if (humpString[i] in htmlStyle) return true;    return false;
}
Copy after login
这个是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
Copy after login

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


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] ;
Copy after login

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

我们可以用正则表达式和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,性别女"
Copy after login

相关推荐:

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Learn the canvas framework and explain the commonly used canvas framework in detail Learn the canvas framework and explain the commonly used canvas framework in detail Jan 17, 2024 am 11:03 AM

Explore the Canvas framework: To understand what are the commonly used Canvas frameworks, specific code examples are required. Introduction: Canvas is a drawing API provided in HTML5, through which we can achieve rich graphics and animation effects. In order to improve the efficiency and convenience of drawing, many developers have developed different Canvas frameworks. This article will introduce some commonly used Canvas frameworks and provide specific code examples to help readers gain a deeper understanding of how to use these frameworks. 1. EaselJS framework Ea

See all articles