收藏一些好玩的js代码 利用了闭包,然后重写自身,只有在第一次调用时需要判断,其后都是调用了闭包的函数。
1 2 3 4 5 6 7 //第一次调用时会输出1,往后的调用都是输出2 function a() { console.log("1"); a = function() { console.log("2"); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 //文字图标 var avatar="" +" <br > " +" * * * * ***** * * *** ***** <br > " +" * * * * * * * * * * * <br > " +" ****** * * **** * * * * * * <br > " +" * * * * * * * * * * * * <br > " +" * * ****** ***** * * *** ***** <br > " +" <br > "; //利用<i > .</i > 标签替换空格 avatar = avatar.replace(/\s/g,"<i > .</i > "); $(function(){ $(".asciiart").html(avatar); });
1 2 3 4 //加深对eval的理解 var a = {a:1,b:2} var b = 'a'; eval(b); //{a:1,b:2}
1 JSON.stringify(nv,null," "); //参数的含义 第三个是美化
1 2 3 4 5 6 7 8 //文档解析成功回调 angular.element(document).ready(function(){ angular.injector(["ng"]).invoke(function($http){ //将$http对象转成字符串显示出来 var e = document.querySelector("#logger"); angular.element(e).text($http.toString()); //函数toString }); });
1 2 3 4 5 6 7 //获取func参数列表 function getFuncParams(func) { var matches = func.toString().match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m); if (matches && matches.length > 1) return matches[1].replace(/\s*/, '').split(','); //matches[1]代表的含义 return []; };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 // 假设已定义好某些Service var services = {abc: 123, def: 456, ghi: 789}, // 获取func的参数列表(依赖列表) getFuncParams = function (func) { var matches = func.toString().match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m); if (matches && matches.length > 1) return matches[1].replace(/\s+/, '').split(','); return []; }, // 根据参数列表(依赖列表)填充参数(依赖项) setFuncParams = function (params) { for (var i in params) { params[i] = services[params[i]]; } return params; }; // 激活器 function Activitor(func) { var obj = {}; func.apply(obj, setFuncParams(getFuncParams(func))); return obj; } // 定义新Service function Service(abc, ghi) { this.write = function () { console.log(abc); console.log(ghi); } } // 实例化Service并调用方法 var service = Activitor(Service); service.write();
1 2 3 var obj = {a:1,b:2} obj.c == undefined //true obj.c == 'undefined' //false
1 2 3 4 5 6 $('.box_list ul li').click(function(){ var index = $('.box_list ul li').index(this); $(this).addClass('current').siblings('li').removeClass('current'); $('.box_list .goods_box:eq('+index+')').show().siblings('.goods_box').hide(); });
1 2 3 4 5 6 7 8 9 $("#fileup").change(function(){ var v = $(this).val(); //选择的路径 var reader = new FileReader(); reader.readAsDataURL(this.files[0]); //file属性 reader.onload = function(e){ console.log(e.target.result); $('#file_base64').attr('src',e.target.result); }; });
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 //jQuery.param对比两种序列化方式: var myObject = { a: { one: 1, two: 2, three: 3 }, b: [1,2,3] }; var recursiveEncoded = $.param(myObject); var recursiveDecoded = decodeURIComponent($.param(myObject)); alert(recursiveEncoded); alert(recursiveDecoded); //a%5Bone%5D=1&a%5Btwo%5D=2&a%5Bthree%5D=3&b%5B%5D=1&b%5B%5D=2&b%5B%5D=3 //a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3 var shallowEncoded = $.param(myObject, true); var shallowDecoded = decodeURIComponent(shallowEncoded); alert(shallowEncoded); alert(shallowDecoded); //a=%5Bobject+Object%5D&b=1&b=2&b=3 //a=[object+Object]&b=1&b=2&b=3
1 2 3 4 5 //假如说网站禁止过滤了script 这时该怎么办呢,记住一句话,这是我总结出来的“xss就是在页面执行你想要的js”不用管那么多,只要能运行我们的js就OK,比如用img标签或者a标签。我们可以这样写 <img scr =1 onerror =alert('xss') > //当找不到图片名为1的文件时,执行alert('xss')<a href =javascrip:alert('xss') > s</a > //点击s时运行alert('xss')<iframe src =javascript:alert('xss');height=0 width =0 /> <iframe > //利用iframe的scr来弹窗<img src ="1" onerror =eval("\x61\x6c\x65\x72\x74\x28\x27\x78\x73\x73\x27\x29") > </img > //过滤了alert来执行弹窗
1 2 3 4 5 6 7 8 9 10 11 12 // this指Window AST(抽象语法树) var mock = function () { //声明匿名 直接执行 this指Window var global = function () { return this; }(); if (!global.__start__ || global.__start__ <= 0 ) { global.__start__ = 1000 ; } global.__start__ - = Math.floor (Math.random () * 10 ); return global.__start__ ; }
1 2 //用正则格式化 '8227'.replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,'); //8,227
1 2 3 4 5 6 7 8 9 10 //正则 组匹配 function decodeTransform(transString) { var match = /translate\((\d+),(\d+)\)\srotate\((\d+)\)\sscale\((\d+)\)/.exec(transString); return match ? { tx: +match[1], ty: +match[2], rotate: +match[3], scale: +match[4] } : null; }
1 2 //字符串当数组取下标的字符 var a='1234567890'; console.log(a[2]); // '3'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 //bind 改变上下文作用域 Over-->scroll、Out -->Object function T(c) { this.id = "Object"; this.dom = document.getElementById("scroll"); } T.prototype = { init: function() { //① this.dom.onmouseover = function() { console.log("Over-->"+this.id); } //② this.dom.onmouseout = function() { console.log("Out -->"+this.id); } .bind(this) } }; (new T()).init();
1 2 3 4 5 6 7 8 //图片预加载 $.preloadImages = function () { for (var i = 0; i < arguments.length; i++) { $('<img>').attr('src', arguments[i]); } }; $.preloadImages('img/hover-on.png', 'img/hover-off.png');
1 2 3 4 5 6 //自动修补破损图像 $('img').on('error', function () { if(!$(this).hasClass('broken-image')) { $(this).prop('src', 'img/broken.png').addClass('broken-image'); } });
1 2 3 4 5 6 7 8 9 //使两个DIV同等高度 var $columns = $('.column'); var height = 0; $columns.each(function () { if ($(this).height() > height) { height = $(this).height(); } }); $columns.height(height);
1 2 3 4 //根据文本获取元素 伪类选择器的使用 //通过jQuery中的contains()选择器,你能找到一个元素内的文本内容。如果文本不存在,则这个元素将被隐藏 var search = $('#search').val(); $('div:not(:contains("' + search + '"))').hide();
1 2 3 4 5 6 7 8 9 //拖拽效果 $(".haorooms_drag").on({ mousedown: function(e){ var el=$(this); var os = el.offset(); dx = e.pageX-os.left, dy = e.pageY-os.top; $(document).on('mousemove.drag', function(e){ el.offset({top: e.pageY-dy, left: e.pageX-dx}); }); }, mouseup: function(e){ $(document).off('mousemove.drag'); }
1 2 //获取字符串最后一个字符 var char = name[name.length-1];
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 /* * Stop dragging the current slider (if any) * and set the current slider to the one specified. * (0 = red, 1 = green, 2 = blue) */ function startColorDrag(evt) { var sliderId = evt.target.parentNode.getAttribute("id"); endColorDrag( evt ); slideChoice = parseInt(sliderId[sliderId.length - 1]); } /* * Set slider choice to -1, indicating that no * slider is begin dragged. No access to the event * is needed for this function. * mouseup事件应该绑定到最大元素块上 */ function endColorDrag(evt) { slideChoice = -1; } function doColorDrag(evt) { var sliderId = evt.target.parentNode.getAttribute("id"); chosen = parseInt(sliderId[sliderId.length - 1]); if (slideChoice >= 0 && slideChoice == chosen) { var pos = evt.clientY - 10; if (pos < 0 ) { pos = 0 ; } if (pos > 100) { pos = 100; } obj = document.getElementById("slide" + slideChoice); obj.setAttribute("y1", pos); obj.setAttribute("y2", pos); rgb[slideChoice] = 100-pos; var colorStr = "rgb(" + rgb[0] + "%," + rgb[1] + "%," + rgb[2] + "%)"; obj = document.getElementById("shirt"); obj.style.setProperty("fill", colorStr, null); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // Drag Events in Snap Snap("#circle").drag(dragMove, dragStart, dragEnd); function dragStart(x, y, evt) { // figure out where the circle currently is startX = parseInt(Snap("#circle").attr("cx"), 10); startY = parseInt(Snap("#circle").attr("cy"), 10); } function dragMove(dx, dy, x, y, evt) { Snap("#circle").attr({cx: (startX + dx), cy: (startY + dy)}); } function dragEnd(evt) { // no action required }
1 2 3 4 5 6 7 8 9 //特性检查并替代方案 if (!window.requestAnimationFrame ) { window.requestAnimationFrame = function(animationFunction) { function wrapperFunction() { animationFunction(); } setTimeout(wrapperFunction, 30); }; }
1 2 3 4 5 6 7 //原型、函数理解 function Fn(){ Fn.prototype.name='中国'; Fn.prototype.getYear=function(){ return 1949; }; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 //jquery机制 var $ = function(selector, context) { return new $.fn.init(selector, context); }; $.fn = $.prototype; $.fn.init = function(selector, context) { var nodeList = (context || document).querySelectorAll(selector); this.length = nodeList.length; for (var i=0; i<this.length; i+=1) { this[i] = nodeList[i]; } return this; }; $.fn.each = function(fn) { var i=0, length = this.length; for (; i<length; i+=1) { fn.call(this[i], i, this[i]); } return this; }; $.fn.hide = function() { this.each(function() { this.style.display = "none"; }); }; $.fn.init.prototype = $.fn; $("button")[0].onclick = function() { $("img").hide(); };
1 2 3 4 5 6 7 8 9 function chunk(array, process, context) { setTimeout(function() { var item = array.shift(); process.call(context, item); if (array.length > 0) { setTimeout(arguments.callee, 100); }), 100); } //chunk()函数的用途就是将一个数组分成小块处理,它接受三个参数:要处理的数组,处理函数以及可选的上下文环境。每次函数都会将数组中第一个对象取出交给process函数处理,如果数组中还有对象没有被处理则启动下一个timer,直到数组处理完。这样可保证脚本不会长时间占用处理机,使浏览器出一个高响应的流畅状态。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 var express = require('express'); var app = express(); app.get('/', function(req, res) { res.send('hello, express'); }); app.get('/users/:name', function(req, res) { res.send('hello, ' + req.params.name); }); app.listen(3000); //当访问根路径时,依然返回hello, express,当访问如localhost:3000/users/nswbmw路径时,返回hello, nswbmw。路径中:name起了占位符的作用,这个占位符的名字是name,可以通过req.params.name取到实际的值。 //express使用了path-to-regexp模块实现的路由匹配。
1 2 3 4 5 6 7 8 9 10 11 // 自运行函数 void function (module, exports){ window["60ae5ba7"] = {}; "use strict"; console.log('111111'); window["60ae5ba7"].a = 'aaaaaaa'; console.log('222222'); }({exports:{}}, {})
1 2 3 4 5 var a = [,1,2,3] for(var b in a){ console.log(b) } //1 2 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // 一种让超大banner图片不拉伸、全屏宽、居中显示的方法 <html > <head > <title > Title</title > <style > .bannerbox { width:100%; position:relative; overflow:hidden; height:200px; } .banner { width:3000px; /*图片宽度*/ position:absolute; left:50%; margin-left:-1500px; /*图片宽度的一半*/ } </style > </head > <body > <div class ="bannerbox" > <div class ="banner" > <img src ="t1.jpg" > </div > </div > </body > </html >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 // setInterval 在准备把回调函数加入到事件队列的时候,会判断队列中是否还有未执行的回调,如果有的话,它就不会再往队列中添加回调函数。 不然,会出现多个回调同时执行的情况。 var intervalStart = now(); setInterval(function () { console.log('interval距定义定时器的时间:', now() - loopStart); }, 100); var loopStart = now(); heavyTask(); console.log('heavyTask耗费时间:', now() - loopStart); function heavyTask() { var s = now(); while(now() - s < 1000) { } } function now () { return new Date(); } // 输出: // heavyTask耗费时间: 1013 // interval距定义定时器的时间: 1016 // interval距定义定时器的时间: 1123 // interval距定义定时器的时间: 1224 var i = 0; timeoutId = setTimeout(function () { console.log(1); }, 300); setTimeout(function () { var start = new Date(); while(i<1000000000){ i++ } console.log('使用时间:'+i+ ' '+(new Date() - start)); clearTimeout(timeoutId); }, 100);
1 2 javascript怎么实现range函数 let range = (start , end ) => new Array (end - start ).fill(start ).map ((el, i) => start + i);