关注前端 | 前端博客
当前位置: JavaScript > 常用方法总结

常用方法总结

2018-11-06 分类:JavaScript 作者:管理员 阅读(53)

url参数解析方法

function getUrlParams(url){
	let res={};
	let data=url.split('?')[1].split('&');
	for(let i=0;i<data.length;i++){
		let list=data[i].split('=');
		res[list[0]]=list[1];
	}
	return res;	
}
function getUrlParams(url){

  var res={},url=decodeURI(url);

  //如果url里面有?
  if(url.indexOf('?')!=-1){

    //如果url后面有 # 就去掉
    if(url.indexOf('#')!=-1)url=url.slice(0,url.length-1);

    
    //获取 key / value 组合的 数组
    var data = url.split('?')[1].split('&');


    //遍历这个数组
    for(var i=0;i<data.length;i++){

      //分离每一项成数组 [key,value]
      var list=data[i].split('=');

      //res继承每一项的 key和value
      res[list[0]]=decodeURI(list[1]);

    }

  }
  
  return res; 

}

离线存储方法LocalStorge封装

/***********************************
 * *localStorage封装本地离线存储方法 
 ***********************************/
function Store(projectName){
	//对象检测
	this.isObject=function(o){
		return Object.prototype.toString.call(o)=='[object Object]';
	}
	//字符串检测
	this.isString=function(s){
		return Object.prototype.toString.call(s)=='[object String]';
	}
	//数字检测
	this.isNumber=function(n){
		return Object.prototype.toString.call(n)=='[object Number]';
	}
	//数组检测
	this.isArray=function(a){
		return Object.prototype.toString.call(a)=='[object Array]';
	}
	//检查projectName属性是否存在
	this.isExist=function(){
		return localStorage[projectName] === undefined;
	}
	//初始化
	this.init=function(){
		if(this.isExist()){//用户首次登录/没有这个字段
			let data={};
			localStorage.setItem(projectName,JSON.stringify(data));
		}
	}
	//获取一级键值
	this.get=function(key){
		if(!this.isExist()){
			let obj=JSON.parse(localStorage.getItem(projectName));
			return 	obj[key]?obj[key]:false;	
		}else{
			return false;
		}
	}
	//设置一级键值
	this.set=function(){
		let args=arguments;
		if(!this.isExist()){
			let obj=JSON.parse(localStorage.getItem(projectName));
			if(args.length==1&&this.isObject(args[0])){
				for(let key in args[0]){
					obj[key]=args[0][key];
				}
				let data=JSON.stringify(obj);
				localStorage.setItem(projectName,data);
			}else if(args.length==2&&this.isString(args[0])&&(this.isString(args[1])||this.isNumber(args[1]))){
				obj[args[0]]=args[1];
				let data=JSON.stringify(obj);
				localStorage.setItem(projectName,data);
			}else if(args.length==2&&this.isString(args[0])&&this.isObject(args[1])){
				obj[args[0]]=args[1];
				let data=JSON.stringify(obj);
				localStorage.setItem(projectName,data);
			}
			
		}else{
	        if(args.length==1&&this.isObject(args[0])){
	            let obj={};
				for(let key in args[0]){
					obj[key]=args[0][key];
				}
				let data=JSON.stringify(obj);
	            localStorage.setItem(projectName,data);
			}
			
			
		}
	}
	//删除一级键值
	this.del=function(){
		let args=arguments;
		if(!this.isExist()){
			let obj=JSON.parse(localStorage.getItem(projectName));
			if(this.isArray(args[0])){
				for(let i=0;i<args[0].length;i++){
					delete obj[args[0][i]];
				}
			}else{
				delete obj[args[0]];
			}
			let data=JSON.stringify(obj);
			localStorage.setItem(projectName,data);
		}else{
			return false;
		}
	}
	//获取二级键值
	this.getDeep=function(key1,key2){
		if(!this.isExist()){
			let obj=JSON.parse(localStorage.getItem(projectName));
			if(obj[key1]&&obj[key1][key2]){
				return obj[key1][key2]?obj[key1][key2]:false;	
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	//设置二级键值
	this.setDeep=function(){
		var args=arguments;
		if(args.length==3){
			if(!this.isExist()){
				let obj=JSON.parse(localStorage.getItem(projectName));
				if(!obj[args[0]]){
					obj[args[0]]={};
					obj[args[0]][args[1]]=args[2];
					let data=JSON.stringify(obj);
					localStorage.setItem(projectName,data);
				}else{
					obj[args[0]][args[1]]=args[2];
					let data=JSON.stringify(obj);
					localStorage.setItem(projectName,data);
				}
			}else{
				this.init();
			}
		}else if(args.length==2){
			if(!this.isExist()){
				let obj=JSON.parse(localStorage.getItem(projectName));
				if(!obj[args[0]]){
					obj[args[0]]={};
					for(var k in args[1]){
						obj[args[0]][k]=args[1][k];
					}
					let data=JSON.stringify(obj);
					localStorage.setItem(projectName,data);
				}else{
					for(var k in args[1]){
						obj[args[0]][k]=args[1][k];
					}
					let data=JSON.stringify(obj);
					localStorage.setItem(projectName,data);
				}
			}else{
				this.init();
			}
		}
	}
	//删除二级键值
	this.delDeep=function(key1,key2){
		if(!this.isExist()){
			let obj=JSON.parse(localStorage.getItem(projectName));
			if(obj[key1]&&obj[key1][key2]){
				delete obj[key1][key2];
				let data=JSON.stringify(obj);
				localStorage.setItem(projectName,data);
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	this.init();
}
window.store=new Store('projectName');
//设置一级键值的两种方法
store.set('key','name');
store.set({'key1':'value1','key2':'value2'});
//获取一级键值方法
store.set('key');
//删除一级键值
store.del('key');

//设置二级键值的两种方法
store.setDeep('key1','key11','value');
store.setDeep('key1',{
	'key11':'value11',
	'key12':'value12',
	'key13':'value13'
});

//获取二级键值方法
store.getDeep('key1','key11');
//删除二级键值
store.delDeep('key1','key11');

cookie方法简单封装

function C(){
	this.params={}
}
C.prototype.setCookie=function(name, value, domain, path, expires){

	if (expires) {
      expires = new Date(+new Date() + expires);
   }
	if(Object.prototype.toString.call(value).slice(8, -1) === 'Object'){
		value=JSON.stringify(value);
	}
    var tempcookie = name + '=' + escape(value) + ((expires) ? '; expires=' + expires.toGMTString() : '') + ((path) ? '; path=' + path : '') + ((domain) ? '; domain=' + domain : '');
    if (tempcookie.length < 4096) {
      document.cookie = tempcookie;
    }
}
C.prototype.getCookie=function(name){
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
    return unescape(arr[2]);
    else
    return null;
}
C.prototype.delCookie=function(name){
	var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null)
    document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}
C.prototype.add=function(name,key,value){
	this.params=JSON.parse(this.getCookie(name));
	this.params[key]=value;
	this.setCookie(name, JSON.stringify(this.params),document.domain,'',3600000);
}
C.prototype.remove=function(name,key){
	this.params=JSON.parse(this.getCookie(name));
	if(this.params[key]){
		delete this.params[key];
		this.setCookie(name, JSON.stringify(this.params),document.domain,'',3600000);
	}
}

//挂载实例
window.COOKIE=new C();

//设置cookie  value可以是对象
COOKIE.setCookie(name, value, domain, path, expires)

//获取cookie 需要传一个cookie的name
COOKIE.getCookie(name)

//如果cookie 的值是JSON字符串,可以对其使用 add 或 remove 这个对象的属性
COOKIE.add(name,key,value);
COOKIE.remove(name,key);

上传图片转base64方法

<!doctype html>
<html lang="zh-cn">
<head>
	<meta charset="UTF-8">
	<title>本地图片上传转为base64</title>
</head>
<body>
	<input type="file" id="js_file" accept="image/gif,image/jpeg,image/jpg,image/png">
</body>
<script>
	function $(el){
		return document.querySelector(el);
	}
	function attr(obj,el){
		for(var k in obj){
			el.setAttribute(k,obj[k]);
		}
	}
	document.querySelector('#js_file').onchange=function(){
		let file = this.files[0];
		r = new FileReader();
		r.readAsDataURL(file);
		r.onload = function(e) {
			let base64 = e.target.result;
			console.log(base64)
		}
	}
</script>
</html>

图片压缩方法

<!doctype html>
<html lang="zh-cn">
<head>
	<meta charset="UTF-8">
	<title>图片压缩</title>
</head>
<body>
	<input type="file" id="js_file" accept="image/gif,image/jpeg,image/jpg,image/png">
	<img alt="" id="Img">
</body>
<script>
	function compression(base64,ratio,callback){
		let img =new Image();
		img.src=base64;
		img.onload=function(){
			let canvas = document.createElement('canvas');
			let w = this.width / ratio;
			let h = this.height / ratio;
			canvas.setAttribute("width", w);
			canvas.setAttribute("height", h);
			canvas.getContext("2d").drawImage(this, 0, 0, w, h);
			let base64=canvas.toDataURL("image/png");
			console.log("压缩后:" + base64.length);
			callback&&callback(base64);
		}
	}

	document.querySelector('#js_file').onchange=function(){
		let file = this.files[0];
		if(file == undefined)return; //如果未找到文件,结束函数,跳出
		r = new FileReader();
		r.readAsDataURL(file);
		r.onload = function(e) {
			let base64 = e.target.result;
			console.log("压缩前:" + base64.length);
			compression(base64,8,function(base64){//2表示缩小的倍数
				document.querySelector('#Img').setAttribute('src',base64);
			})
		}
	}
</script>
</html>

图片压缩上传demo转自别处

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <title>移动端图片压缩上传demo</title>
  <style>
*{margin: 0;padding: 0;}
li{list-style-type: none;}
a,input{outline: none;-webkit-tap-highlight-color:rgba(0,0,0,0);}
#choose{display: none;}
canvas{width: 100%;border: 1px solid #000000;}
#upload{display: block;margin: 10px;height: 60px;text-align: center;line-height: 60px;border: 1px solid;border-radius: 5px;cursor: pointer;}
.touch{background-color: #ddd;}
.img-list{margin: 10px 5px;}
.img-list li{position: relative;display: inline-block;width: 100px;height: 100px;margin: 5px 5px 20px 5px;border: 1px solid rgb(100,149,198);background: #fff no-repeat center;background-size: cover;}
.progress{position: absolute;width: 100%;height: 20px;line-height: 20px;bottom: 0;left: 0;background-color:rgba(100,149,198,.5);}
.progress span{display: block;width: 0;height: 100%;background-color:rgb(100,149,198);text-align: center;color: #FFF;font-size: 13px;}
.size{position: absolute;width: 100%;height: 15px;line-height: 15px;bottom: -18px;text-align: center;font-size: 13px;color: #666;}
.tips{display: block;text-align:center;font-size: 13px;margin: 10px;color: #999;}
.pic-list{margin: 10px;line-height: 18px;font-size: 13px;}
.pic-list a{display: block;margin: 10px 0;}
.pic-list a img{vertical-align: middle;max-width: 30px;max-height: 30px;margin: -4px 0 0 10px;}
</style>
</head>
<body>
<input type="file" id="choose" accept="image/*" multiple>
<ul class="img-list"></ul>
<a id="upload">上传图片</a>
<span class="tips">只允许上传jpg、png及gif</span>
<script src="https://cdn.bootcss.com/jquery/2.2.3/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/vConsole/2.3.0/vconsole.min.js"></script>
<script>
  var filechooser = document.getElementById("choose");
  //用于压缩图片的canvas
  var canvas = document.createElement("canvas");
  var ctx = canvas.getContext('2d');
  //瓦片canvas
  var tCanvas = document.createElement("canvas");
  var tctx = tCanvas.getContext("2d");
  var maxsize = 100 * 1024;
  $("#upload").on("click", function() {
        filechooser.click();
      })
      .on("touchstart", function() {
        $(this).addClass("touch")
      })
      .on("touchend", function() {
        $(this).removeClass("touch")
      });
  filechooser.onchange = function() {
    if (!this.files.length) return;
    var files = Array.prototype.slice.call(this.files);
    if (files.length > 5) {
      alert("最多同时只可上传4张图片");
      return;
    }
    files.forEach(function(file, i) {
		if (!/\/(?:jpeg|png|gif)/i.test(file.type)) return;
		var reader = new FileReader();
		var li = document.createElement("li");
		//获取图片大小
		var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";
		li.innerHTML = '<div class="progress"><span></span></div><div class="size">' + size + '</div>';
		$(".img-list").append($(li));
		reader.onload = function() {
			var result = this.result;
			var img = new Image();
			img.src = result;
			$(li).css("background-image", "url(" + result + ")");
			//如果图片大小小于100kb,则直接上传
			if (result.length <= maxsize) {
			  img = null;
			  upload(result, file.type, $(li));
			  return;
			}
			//图片加载完毕之后进行压缩,然后上传
			if (img.complete) {
			  callback();
			} else {
			  img.onload = callback;
			}
			function callback() {
				console.log(img.width,img.height)
			  var data = compress(img);
			  upload(data, file.type, $(li));
			  img = null;
			}
		};
      reader.readAsDataURL(file);
    })
  };
  //使用canvas对大图片进行压缩
  function compress(img) {
    var initSize = img.src.length;
    var width = img.width;
    var height = img.height;
    //如果图片大于四百万像素,计算压缩比并将大小压至400万以下
    var ratio;
    if ((ratio = width * height / 4000000) > 1) {
      ratio = Math.sqrt(ratio);
      width /= ratio;
      height /= ratio;
    } else {
      ratio = 1;
    }
    canvas.width = width;
    canvas.height = height;
	//铺底色
    ctx.fillStyle = "#fff";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    //如果图片像素大于100万则使用瓦片绘制
    var count;
    if ((count = width * height / 1000000) > 1) {
		count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
		//计算每块瓦片的宽和高
		var nw = ~~(width / count);
		var nh = ~~(height / count);
		tCanvas.width = nw;
		tCanvas.height = nh;
		for (var i = 0; i < count; i++) {
			for (var j = 0; j < count; j++) {
			  tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
			  ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
			}
		}
    } else {
      ctx.drawImage(img, 0, 0, width, height);
    }
    //进行最小压缩
    var ndata = canvas.toDataURL('image/jpeg', 0.1);
    console.log('压缩前:' + initSize);
    console.log('压缩后:' + ndata.length);
    console.log('压缩率:' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
    tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
    return ndata;
}
 //图片上传,将base64的图片转成二进制对象,塞进formdata上传
function upload(basestr, type, $li) {
    var text = window.atob(basestr.split(",")[1]);
    var buffer = new Uint8Array(text.length);
    var pecent = 0, loop = null;
    for (var i = 0; i < text.length; i++) {
      buffer[i] = text.charCodeAt(i);
    }
    var blob = getBlob([buffer], type);
    var xhr = new XMLHttpRequest();
    var formdata = getFormData();
    formdata.append('imagefile', blob);
    xhr.open('post', '/cupload');
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
        var jsonData = JSON.parse(xhr.responseText);
        var imagedata = jsonData[0] || {};
        var text = imagedata.path ? '上传成功' : '上传失败';
        console.log(text + ':' + imagedata.path);
        clearInterval(loop);
        //当收到该消息时上传完毕
        $li.find(".progress span").animate({'width': "100%"}, pecent < 95 ? 200 : 0, function() {
          $(this).html(text);
        });
        if (!imagedata.path) return;
        $(".pic-list").append('<a href="' + imagedata.path + '">' + imagedata.name + '(' + imagedata.size + ')<img src="' + imagedata.path + '" /></a>');
      }
    };
    //数据发送进度,前50%展示该进度
    xhr.upload.addEventListener('progress', function(e) {
      if (loop) return;
      pecent = ~~(100 * e.loaded / e.total) / 2;
      $li.find(".progress span").css('width', pecent + "%");
      if (pecent == 50) {
        mockProgress();
      }
    }, false);
    //数据后50%用模拟进度
    function mockProgress() {
      if (loop) return;
      loop = setInterval(function() {
        pecent++;
        $li.find(".progress span").css('width', pecent + "%");
        if (pecent == 99) {
          clearInterval(loop);
        }
      }, 100)
    }
    xhr.send(formdata);
}
/**
* 获取blob对象的兼容性写法
* @param buffer
* @param format
* @returns {*}
*/
function getBlob(buffer, format) {
	try {
	  return new Blob(buffer, {type: format});
	} catch (e) {
	  var bb = new (window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder);
	  buffer.forEach(function(buf) {
	    bb.append(buf);
	  });
	  return bb.getBlob(format);
	}
}
/**
* 获取formdata
*/
function getFormData() {
	var isNeedShim = ~navigator.userAgent.indexOf('Android')
    && ~navigator.vendor.indexOf('Google')
    && !~navigator.userAgent.indexOf('Chrome')
    && navigator.userAgent.match(/AppleWebKit\/(\d+)/).pop() <= 534;
	return isNeedShim ? new FormDataShim() : new FormData()
}
/**
* formdata 补丁, 给不支持formdata上传blob的android机打补丁
* @constructor
*/
function FormDataShim() {
    console.warn('using formdata shim');
    var o = this,
        parts = [],
        boundary = Array(21).join('-') + (+new Date() * (1e16 * Math.random())).toString(36),
        oldSend = XMLHttpRequest.prototype.send;
    this.append = function(name, value, filename) {
      parts.push('--' + boundary + '\r\nContent-Disposition: form-data; name="' + name + '"');
      if (value instanceof Blob) {
        parts.push('; filename="' + (filename || 'blob') + '"\r\nContent-Type: ' + value.type + '\r\n\r\n');
        parts.push(value);
      }
      else {
        parts.push('\r\n\r\n' + value);
      }
      parts.push('\r\n');
    };
    // Override XHR send()
    XMLHttpRequest.prototype.send = function(val) {
      var fr,
          data,
          oXHR = this;
      if (val === o) {
        // Append the final boundary string
        parts.push('--' + boundary + '--\r\n');
        // Create the blob
        data = getBlob(parts);
        // Set up and read the blob into an array to be sent
        fr = new FileReader();
        fr.onload = function() {
          oldSend.call(oXHR, fr.result);
        };
        fr.onerror = function(err) {
          throw err;
        };
        fr.readAsArrayBuffer(data);
        // Set the multipart content type and boudary
        this.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
        XMLHttpRequest.prototype.send = oldSend;
      }
      else {
        oldSend.call(this, val);
      }
    };
}
</script>
</body>
</html>

微信签名SHA1加密方法

/*
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
 * in FIPS PUB 180-1
 * Version 2.1-BETA Copyright Paul Johnston 2000 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for details.
 */
/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase     */
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance  */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode    */
/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_sha1(s) {
 return binb2hex(core_sha1(str2binb(s), s.length * chrsz));
}
function b64_sha1(s) {
 return binb2b64(core_sha1(str2binb(s), s.length * chrsz));
}
function str_sha1(s) {
 return binb2str(core_sha1(str2binb(s), s.length * chrsz));
}
function hex_hmac_sha1(key, data) {
 return binb2hex(core_hmac_sha1(key, data));
}
function b64_hmac_sha1(key, data) {
 return binb2b64(core_hmac_sha1(key, data));
}
function str_hmac_sha1(key, data) {
 return binb2str(core_hmac_sha1(key, data));
}
/*
 * Perform a simple self-test to see if the VM is working
 */
function sha1_vm_test() {
 return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
}
/*
 * Calculate the SHA-1 of an array of big-endian words, and a bit length
 */
function core_sha1(x, len) {
 /* append padding */
 x[len >> 5] |= 0x80 << (24 - len % 32);
 x[((len + 64 >> 9) << 4) + 15] = len;
 var w = Array(80);
 var a = 1732584193;
 var b = -271733879;
 var c = -1732584194;
 var d = 271733878;
 var e = -1009589776;
 for (var i = 0; i < x.length; i += 16) {
  var olda = a;
  var oldb = b;
  var oldc = c;
  var oldd = d;
  var olde = e;
  for (var j = 0; j < 80; j++) {
   if (j < 16) w[j] = x[i + j];
   else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
   var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
   e = d;
   d = c;
   c = rol(b, 30);
   b = a;
   a = t;
  }
  a = safe_add(a, olda);
  b = safe_add(b, oldb);
  c = safe_add(c, oldc);
  d = safe_add(d, oldd);
  e = safe_add(e, olde);
 }
 return Array(a, b, c, d, e);
}
/*
 * Perform the appropriate triplet combination function for the current
 * iteration
 */
function sha1_ft(t, b, c, d) {
 if (t < 20) return (b & c) | ((~b) & d);
 if (t < 40) return b ^ c ^ d;
 if (t < 60) return (b & c) | (b & d) | (c & d);
 return b ^ c ^ d;
}
/*
 * Determine the appropriate additive constant for the current iteration
 */
function sha1_kt(t) {
 return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;
}
/*
 * Calculate the HMAC-SHA1 of a key and some data
 */
function core_hmac_sha1(key, data) {
 var bkey = str2binb(key);
 if (bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);
 var ipad = Array(16),
  opad = Array(16);
 for (var i = 0; i < 16; i++) {
  ipad[i] = bkey[i] ^ 0x36363636;
  opad[i] = bkey[i] ^ 0x5C5C5C5C;
 }
 var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
 return core_sha1(opad.concat(hash), 512 + 160);
}
/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y) {
 var lsw = (x & 0xFFFF) + (y & 0xFFFF);
 var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
 return (msw << 16) | (lsw & 0xFFFF);
}
/*
 * Bitwise rotate a 32-bit number to the left.
 */
function rol(num, cnt) {
 return (num << cnt) | (num >>> (32 - cnt));
}
/*
 * Convert an 8-bit or 16-bit string to an array of big-endian words
 * In 8-bit function, characters >255 have their hi-byte silently ignored.
 */
function str2binb(str) {
 var bin = Array();
 var mask = (1 << chrsz) - 1;
 for (var i = 0; i < str.length * chrsz; i += chrsz)
 bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i % 32);
 return bin;
}
/*
 * Convert an array of big-endian words to a string
 */
function binb2str(bin) {
 var str = "";
 var mask = (1 << chrsz) - 1;
 for (var i = 0; i < bin.length * 32; i += chrsz)
 str += String.fromCharCode((bin[i >> 5] >>> (24 - i % 32)) & mask);
 return str;
}
/*
 * Convert an array of big-endian words to a hex string.
 */
function binb2hex(binarray) {
 var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
 var str = "";
 for (var i = 0; i < binarray.length * 4; i++) {
  str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);
 }
 return str;
}
/*
 * Convert an array of big-endian words to a base-64 string
 */
function binb2b64(binarray) {
 var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
 var str = "";
 for (var i = 0; i < binarray.length * 4; i += 3) {
  var triplet = (((binarray[i >> 2] >> 8 * (3 - i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2] >> 8 * (3 - (i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2] >> 8 * (3 - (i + 2) % 4)) & 0xFF);
  for (var j = 0; j < 4; j++) {
   if (i * 8 + j * 6 > binarray.length * 32) str += b64pad;
   else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);
  }
 }
 return str;
}

微信签名SHA1加密方法使用

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>sha1加密</title>
<script type="text/ecmascript" src="sha1.js"></script>
<script type="text/javascript">
 var sha = hex_sha1('jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW&timestamp=1414587457&url=http://mp.weixin.qq.com?params=value')
 alert(sha);//0f9de62fce790f9a083d5c99e95740ceb90c27ed
</script>
</head>
<body>
</body>
</html>

MD5.JS

/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */
/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase  */
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode  */
/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }
/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test()
{
 return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}
/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
function core_md5(x, len)
{
 /* append padding */
 x[len >> 5] |= 0x80 << ((len) % 32);
 x[(((len + 64) >>> 9) << 4) + 14] = len;
 var a = 1732584193;
 var b = -271733879;
 var c = -1732584194;
 var d = 271733878;
 for(var i = 0; i < x.length; i += 16)
 {
 var olda = a;
 var oldb = b;
 var oldc = c;
 var oldd = d;
 a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
 d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
 c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
 b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
 a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
 d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
 c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
 b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
 a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
 d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
 c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
 b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
 a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
 d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
 c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
 b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
 a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
 d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
 c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
 b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
 a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
 d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
 c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
 b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
 a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
 d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
 c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
 b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
 a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
 d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
 c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
 b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
 a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
 d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
 c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
 b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
 a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
 d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
 c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
 b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
 a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
 d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
 c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
 b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
 a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
 d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
 c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
 b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
 a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
 d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
 c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
 b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
 a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
 d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
 c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
 b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
 a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
 d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
 c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
 b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
 a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
 d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
 c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
 b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
 a = safe_add(a, olda);
 b = safe_add(b, oldb);
 c = safe_add(c, oldc);
 d = safe_add(d, oldd);
 }
 return Array(a, b, c, d);
}
/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t)
{
 return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
 return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
 return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
 return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
 return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
 * Calculate the HMAC-MD5, of a key and some data
 */
function core_hmac_md5(key, data)
{
 var bkey = str2binl(key);
 if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);
 var ipad = Array(16), opad = Array(16);
 for(var i = 0; i < 16; i++)
 {
 ipad[i] = bkey[i] ^ 0x36363636;
 opad[i] = bkey[i] ^ 0x5C5C5C5C;
 }
 var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
 return core_md5(opad.concat(hash), 512 + 128);
}
/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
 var lsw = (x & 0xFFFF) + (y & 0xFFFF);
 var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
 return (msw << 16) | (lsw & 0xFFFF);
}
/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt)
{
 return (num << cnt) | (num >>> (32 - cnt));
}
/*
 * Convert a string to an array of little-endian words
 * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
 */
function str2binl(str)
{
 var bin = Array();
 var mask = (1 << chrsz) - 1;
 for(var i = 0; i < str.length * chrsz; i += chrsz)
 bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
 return bin;
}
/*
 * Convert an array of little-endian words to a string
 */
function binl2str(bin)
{
 var str = "";
 var mask = (1 << chrsz) - 1;
 for(var i = 0; i < bin.length * 32; i += chrsz)
 str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
 return str;
}
/*
 * Convert an array of little-endian words to a hex string.
 */
function binl2hex(binarray)
{
 var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
 var str = "";
 for(var i = 0; i < binarray.length * 4; i++)
 {
 str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
   hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
 }
 return str;
}
/*
 * Convert an array of little-endian words to a base-64 string
 */
function binl2b64(binarray)
{
 var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
 var str = "";
 for(var i = 0; i < binarray.length * 4; i += 3)
 {
 var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16)
    | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
    | ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
 for(var j = 0; j < 4; j++)
 {
  if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
  else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
 }
 }
 return str;
}

md5.js使用

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>md5加密</title>
<script type="text/ecmascript" src="md5.js"></script>
<script type="text/javascript">
 var hash = hex_md5("123dafd");
 alert(hash)
</script>
</head>
<body>
</body>
</html>

获取随机字符串(字符可重复),获取位数自定义

function getNonceStr(count){
	let s=['a','b','c','d','e','f','g','h','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',"A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",0,1,2,3,4,5,6,7,8,9]	;
	let ss=[]
	for(let i=0;i<count;i++){
		ss.push(s[Math.floor(Math.random()*56)])
	}
	return ss.join('');
}

获取随机不重复字符串,获取位数自定义

function getNonceStr(Count){
	let s=['a','b','c','d','e','f','g','h','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',"A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",0,1,2,3,4,5,6,7,8,9]	;
	let ss=[];
	let _arr=[];
	while(_arr.length<Count){
		var randomNum=Math.floor(Math.random()*56);
		if(_arr.length===0){
			_arr.push(randomNum)
		}else{
			for(var i=0;i<_arr.length;i++){
				if(_arr.indexOf(randomNum)==-1){
					_arr.push(randomNum)
				}
			}
		}
	}
	for(let i=0;i<Count;i++){
		ss.push(s[_arr[i]])
	}
	return ss.join('');
}

「两年博客,如果觉得我的文章对您有用,请帮助本站成长」

赞(0) 打赏

感谢您让我添加个鸡腿!

支付宝
微信
0

感谢您让我添加个鸡腿!

支付宝
微信
标签:

上一篇:

下一篇:

共有 1 条评论 - 常用方法总结

  1. gellytech Windows 7 Chrome 63.0.3239.132

    学习 :redface:

博客简介

一位不知名的前端工程师,专注全栈技术,分享各种所遇问题与个人心得,梦想成为一位知名大神!

最近更新

精彩评论

服务热线:
 177****6038

 QQ在线交流

 旺旺在线