本篇文章介绍的内容是关于js 常用的工具方法,现在分享给大家,有需要的朋友可以参考一下
1、cookie 操作
// setCookie() // @About 设置cookie 默认一个月失效 function 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 获取cookie function getCookie(name) { var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")); if (arr != null) { return (arr[2]); } else { return ""; } } // delCookie() // @About 删除cookie function 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,10 randomNumber(10) // 返回0-10的随机整数,包括0,10 randomNumber() // 返回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; // 3
var c= 0 || 2 && 3; // 3
更多操作大家可以参考JS运算符&&和|| 及其优先级。
5,获取,设置url
参数,url
参数就是其中 ?
后面的参数
function getUrlPrmt(url) { url = url ? url : window.location.href; let _pa = url.substring(url.indexOf('?') + 1), _arrS = _pa.split('&'), _rs = {}; for (let i = 0, _len = _arrS.length; i < _len; i++) { let pos = _arrS[i].indexOf('='); if (pos == -1) { continue; } let name = _arrS[i].substring(0, pos), value = window.decodeURIComponent(_arrS[i].substring(pos + 1)); _rs[name] = value; } return _rs; }
这里是设置url
参数的函数,如果对象中有null
和undefined
,则会自动过滤。
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中的结果:
这个是firefox中的结果:
8,怎么判断一个对象是不是数组类型?
我们采取最常用的方法:根据对象的class属性(类属性),跨原型链调用toString()方法。
function _getClass(o){ return Object.prototype.toString.call(o).slice(8,-1); } _getClass(new Date()); // Date_getClass('maolei'); // 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] ;
10,最后是我在一个前端大神芋头君live前端笔试题十讲中听到的一个题目:实现一个最简单的模板引擎,感觉很有趣,就直接以这道题作为结尾吧
render('我是{{name}},年龄{{age}},性别{{sex}}',{ name:'姓名', age:18, sex:'女'})
我们可以用正则表达式和replace
解决:
var render = function(tpl,data){ return tpl.replace(/\{\{(.+?)\}\}/g,function(m,m1){ return data[m1] }) } render('我是{{name}},年龄{{age}},性别{{sex}}',{ name:'姓名', age:18,sex:'女', }) // "我是姓名,年龄18,性别女"
相关推荐:
js Several popular js frameworks
The above is the detailed content of js commonly used tools and methods. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
