JavaScript&&常用小公举

URL处理

取参数值

//获取URL中参数的值
    function getParameterByName(name) {
        name = name.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
        var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'),
            results = regex.exec(location.search);
        return results === null ? '' : decodeURIComponent(results[1].replace(
            /\+/g, ' '));
    }

优化值

去空格

 //去左空格
	function ltrim(s){
		return s.replace(/(^\s*)/g, "");
	}
    //去右空格;
	function rtrim(s){
		return s.replace(/(\s*$)/g, "");
	}
    //去左右空格;
	function trim(s){
		return s.replace(/(^\s*)|(\s*$)/g, "");
	}

参考链接:
https://www.cnblogs.com/qlqwjy/p/7777047.html

时间处理

var formatDate = function (e, o) {
	var r = {
		"M+": e.getMonth() + 1,
		"d+": e.getDate(),
		"h+": e.getHours(),
		"m+": e.getMinutes(),
		"s+": e.getSeconds(),
		"q+": Math.floor((e.getMonth() + 3) / 3),
		"S+": e.getMilliseconds()
	};
	/(y+)/i.test(o) && (o = o.replace(RegExp.$1, (e.getFullYear() + "").substr(4 - RegExp.$1.length)));
	for (var t in r)new RegExp("(" + t + ")").test(o) && (o = o.replace(RegExp.$1, 1 == RegExp.$1.length ? r[t] : ("00" + r[t]).substr(("" + r[t]).length)));
	return o
}

监听事件

监听点击事件

监听鼠标左右键点击事件

    $(selector).mousedown(function (e) {
      if (e.which === 1) {
          console.log("You click the left mouse button.")
      } else {
          console.log("You click the right mouse button.");
      }

参考链接
https://blog.csdn.net/qq_38652871/article/details/89021349

数组去重

// 最简单数组去重法
/*
* 新建一新数组,遍历传入数组,值不在新数组就push进该新数组中
* IE8以下不支持数组的indexOf方法
* */
function uniq(array){
    var temp = []; //一个新的临时数组
    for(var i = 0; i < array.length; i++){
        if(temp.indexOf(array[i]) == -1){
            temp.push(array[i]);
        }
    }
    return temp;
}

var aa = [1,2,2,4,9,6,7,5,2,3,5,6,5];
console.log(uniq(aa));

参考链接:
https://www.cnblogs.com/baiyangyuanzi/p/6726258.html

发布了73 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/dfq737211338/article/details/103990102