javascript函数库
- /*1.深拷贝*/
- //(1)
- function deepClone(obj) {
- if (!obj && typeof obj !== 'object') {
- return;
- }
- var newObj = obj.constructor === Array ? [] : {};
- for (var key in obj) {
- if (obj[key]) {
- if (obj[key] && typeof obj[key] === 'object') {
- newObj[key] = obj[key].constructor === Array ? [] : {};
- //递归
- newObj[key] = deepClone(obj[key]);
- } else {
- newObj[key] = obj[key];
- }
- }
- }
- return newObj;
- }
- //使用方法:
- var _arr = [{ a: 1, b: 2 }, { c: 3, d: 4 }];
- var _newArr = deepClone(_arr);
- //(2)比较粗鲁的复制
- JSON.parse(JSON.stringify(_arr));
- /*2.合并数组*/
- //(1)concat方法
- var _arr1 = ["a", "b", "c"];
- var _arr2 = ["1", "2", "3"];
- var newArr = _arr1.concat(_arr2);
- // 注:使用concat方法合并数组时,不会改变原有数组的结构。
- //(2)push.apply()方法
- var _arr1 = ["a", "b", "c"];
- var _arr2 = ["1", "2", "3"];
- _arr1.push.apply(_arr1, _arr2);
- //使用此方法合并的数组会改变合并到的数组
- /*3.判断数据类型(准确)*/
- Object.prototype.toString.call();
- //使用方法:
- var _obj = {};
- Object.prototype.toString.call(_obj) == [object Object];
- /*4.将函数中的arguments参数转成数组*/
- var _arguments = Array.prototype.slice.apply(arguments);
- //使用方法:
- function add(x, y) {
- var _argus = Array.prototype.slice.call(arguments);
- console.log(_argus);
- }
- /*5.节流函数*/
- function delayFn(fn, delay, mustDelay) {
- var timer = null;
- var t_start;
- return function() {
- var context = this,
- args = arguments,
- t_cur = +new Date();
- clearTimeout(timer); //清除上一次定时器
- if (!t_start) {
- t_start = t_cur; //设置触发事件
- }
- if (t_cur - t_start >= mustDelay) { //判断时间差是否大于间隔时间
- fn.apply(context, args);
- t_start = t_cur;
- } else {
- timer = setTimeout(function() { //延迟执行函数
- fn.apply(context, args);
- }, delay);
- }
- };
- }
- //使用方法:
- var count = 0;
- function fn() {
- count++;
- console.log(count);
- }
- document.onmousemove = delayFn(fn, 100, 200); //100ms内连续触发的调用,后一个调用会把前一个调用的等待处理掉,但每隔200ms至少执行一次
- /*6累加函数*/
- var arr1 = arr.reduce(function(con, info) {
- if (con) {
- return con;
- }
- return info._show;
- }, false)
- /*7手机端收起弹出键盘*/
- var hideKeyboard = function() {
- document.activeElement.blur(); //ios
- $("input").blur();
- };
- /*8时间格式化*/
- Date.prototype.Format = function(fmt) {
- var o = {
- "M+": this.getMonth() + 1, //月份
- "d+": this.getDate(), //日
- "h+": this.getHours(), //小时
- "m+": this.getMinutes(), //分
- "s+": this.getSeconds(), //秒
- "q+": Math.floor((this.getMonth() + 3) / 3), //季度
- "S": this.getMilliseconds() //毫秒
- };
- if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
- for (var k in o)
- if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
- return fmt;
- }
- //使用方法:(时间转成yyyy-MM-dd hh:mm:ss)
- var time1 = new Date().Format("yyyy-MM-dd");
- var time2 = new Date().Format("yyyy-MM-dd hh:mm:ss");
- /*9标准时间转时间戳*/
- var time1 = Date.parse(new Date());
- /*10时间戳转标准时间*/
- new Date(time1).Format("yyyy-MM-dd hh:mm:ss");
- /*11.JSON数组去重*/
- /*
- * JSON数组去重
- * @param: [array] json Array
- * @param: [string] 唯一的key名,根据此键名进行去重
- */
- function uniqueArray(array, key) {
- var result = [array[0]];
- for (var i = 1; i < array.length; i++) {
- var item = array[i];
- var repeat = false;
- for (var j = 0; j < result.length; j++) {
- if (item[key] == result[j][key]) {
- repeat = true;
- break;
- }
- }
- if (!repeat) {
- result.push(item);
- }
- }
- return result;
- }
- //使用方法:
- var _json = [{ id: 'aaa', name: 'bb' }, { id: 'bbb', name: 'xx' }, { id: 'aaa', name: 'ccc' }]
- uniqueArray(_json, 'id');
- /*12.JSON数组去重多字段*/
- var arr = [
- { "name": "1", "value": "qqq", "age": "10" },
- { "name": "1", "value": "qqq", "age": "10" },
- { "name": "2", "value": "eee", "age": "20" },
- { "name": "4", "value": "rrr", "age": "50" },
- { "name": "5", "value": "ttt", "age": "100" }
- ];
- for (var i = 0; i < arr.length; i++) {
- for (var j = i + 1; j < arr.length;) {
- if (arr[i].name == arr[j].name && arr[i].value == arr[j].value && arr[i].age == arr[j].age) {
- arr.splice(j, 1);
- } else j++;
- }
- }
- //*13.普通数组去重*/
- Array.prototype.unique = function() {
- var res = [];
- var json = {};
- for (var i = 0; i < this.length; i++) {
- if (!json[this[i]]) {
- res.push(this[i]);
- json[this[i]] = 1;
- }
- }
- return res;
- }
- //使用方法:
- var arr = [112,112,34,'xx',112,112,34,'xx','str','str1'];
- unique(arr);
- /*14.console.log && console.dir*/
- //使用方法:
- var obj = {name:'xx',age:18};
- console.log(obj);
- console.dir(obj);
- //区别
- //console.dir比log方法更易读,信息也更丰富。能够输出原始属性
- /*14.获取当前时间的时间戳(三种方法)*/
- var d1 = new Date().getTime();
- var d2 = new Date().valueOf();
- var d3 = +new Date();
- /*15 替代arguments.callee()方法*/
- //给内部函数命名
- //接受参数n=5,不用for循环输出数组【1,2,3,4,5】
- //(1)arguments.callee()递归写法
- function show(n) {
- var arr = [];
- return (function () {
- arr.unshift(n);
- n--;
- if (n != 0) {
- arguments.callee();
- }
- return arr;
- })()
- }
- show(5)//[1,2,3,4,5]
- //(2)内部函数明明写法
- function show(n) {
- var arr = [];
- return (function fn() {
- arr.unshift(n);
- n--;
- if (n != 0) {
- fn();
- }
- return arr;
- })()
- }
- show(5)//[1,2,3,4,5]
- /*16 预防XSS攻击*/
- //(1)使用正则替换关键字符
- function safeStr(str){
- return str.replace(/</g,'<').replace(/>/g,'>').replace(/"/g, """).replace(/'/g, "'");
- }
- //(2)使用正则转码,解码
- var HtmlUtil = {
- /*1.用正则表达式实现html转码*/
- htmlEncodeByRegExp:function (str){
- var s = "";
- if(str.length == 0) return "";
- s = str.replace(/&/g,"&");
- s = s.replace(/</g,"<");
- s = s.replace(/>/g,">");
- s = s.replace(/ /g," ");
- s = s.replace(/\'/g,"'");
- s = s.replace(/"/g,""");
- return s;
- },
- /*2.用正则表达式实现html解码*/
- htmlDecodeByRegExp:function (str){
- var s = "";
- if(str.length == 0) return "";
- s = str.replace(/&/g,"&");
- s = s.replace(/</g,"<");
- s = s.replace(/>/g,">");
- s = s.replace(/ /g," ");
- s = s.replace(/'/g,"\'");
- s = s.replace(/"/g,""");
- return s;
- }
- };
- /*17。多维数组转一维数组*/ /*参考https://www.cnblogs.com/haoxl/p/6818657.html*/
- //(1)使用数组map()方法,对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组
- var arr = [1,[2,[[3,4],5],6]];
- function unid(arr){
- var arr1 = (arr + '').split(',');//将数组转字符串后再以逗号分隔转为数组
- var arr2 = arr1.map(function(x){
- return Number(x);
- });
- return arr2;
- }
- console.log(unid(arr));
- //(2)只适用于二维数组转一维数组
- var arr = [1,[2,3],[4,5]];
- arr1 = [].concat.apply([],arr);
- console.log(arr1);
- /*18.鼠标滑过显示溢出的文本*/
- function ellipsis(e) {
- var target = e.target;
- var containerLength = $(target).width();
- var textLength = target.scrollWidth;
- var text = $(target).text();
- if (textLength > containerLength) {
- $(target).attr("title", text);
- }
- }
- $("#xxx").on("mouseenter", ellipsis)
复制代码
|
|