javascript常用知识点集

十度 javaScript 2016年02月18日 收藏

目录结构

一、jquery源码中常见知识点

二、javascript中原型链常见的知识点

三、常用的方法集知识点

四、经典实例应用

 

一、jquery源码中常见的知识点

  1.string,number类型转换的快捷方法

  1. // @param s为字符串,n为数字
  2. function fn(obj){
  3. //转换为String类型
  4. var s = obj +"";
  5. //转换为number类型
  6. var n = +obj;
  7. }

  分享一个面试例子:

  1. //加会将其后面自动转换成字符串
  2. "64"+4="644"
  3. //减会将其自动转换成数字
  4. "64"-4=60

 

  2.bool类型转换

  !!obj,将其强制转换为bool类型

  1. alert(!!0) //结果为false
  2. alert(!!"33dd") //结果为true

  !obj,取相反的bool类型

  1. alert(!0) //结果为true
  2. alert(!"222333") //结果为false

  3.=== 与 ==区别

  === 是严格相等,不会进行类型转换,而 == 是不严格相等,会进行类型转换。有些js的书中,建议开发人员永远不要用 == 或者 != 。

  但是jquery源码中,有用到“==”或者“!=”的情况 —— 判断 undefined 和 null 的时候(undefined == null为true)。

  1. //这里的判断,将obj是null,obj是undefined都排除在外了
  2. if(obj != null){
  3. }

  4.检测obj是否为window对象

  1. //null == window.null为true
  2. function isWindow(obj){
  3. return obj != null && obj == window.obj;
  4. }

  5.|| 与 && 用法技巧

  1. //例 var aa=5; name = aa || {} ; alert(name) 则name为55
  2. this.name = name || {} //如果name值存在,则值为name,反之为{}
  3. //例 var aa=5; name = aa && {} ; alert(name) 则name为{},因为aa为5,不为0则为真
  4. this.name = bool && [] //如果bool为true,则值为[],反之则为bool

  经典实例:

  1. ( window.foo || ( window.foo = "bar" ) );
  2. alert(window.foo); //弹出 bar
    //  为什么最后的结果是bar呢,其实可以看成是   undefined || bar  出来的结果肯定是bar

  6.setTimeout(fn,0)与setTimeout(fn)区别(此处有问题,没有考虑单线程的问题,请比较了解的大神,帮忙指点

  setTimeout(fn,0)与setTimeout(fn)都是延迟执行,但是setTimeout(fn)比setTimeout(fn,0)延迟时间还要长,例

  1. function fn(){
  2. var data = new Date();
  3. for(var i=0;i<=1000;i++){
  4. if(i==1000){
  5. console.log("fn="+data.getTime());
  6. }
  7. }
  8. }
  9. function fn1(){
  10. var data = new Date();
  11. for(var i=0;i<=1000;i++){
  12. if(i==1000){
  13. console.log("fn1="+data.getTime());
  14. }
  15. }
  16. }
  17. setTimeout(fn,0),
  18. setTimeout(fn1);

  结果:

 

  7.判断是否为数值

  1. function isNumeric(obj){
  2. return !isNaN(parseFloat(obj)) && isFinite(obj);
  3. }

  8.判断是否为空对象

  1. function isEmptyObject(){
  2. var name;
  3. //遍历不是空对象返回
  4. for (name in obj) {
  5. return false;
  6. }
  7. return true;
  8. }

  9.检测对象类型

  检测obj对象类型,返回类型,通过Object.prototype.toString()来判断类型,但是ie低版本兼容性有问题,因此采用{}.toString来监测,返回为[object Array],[object Object],[object Function]

  1. // 类型判断
  2. function isType(type){
  3. return function(o){
  4. return Object.prototype.toString.call(o) === '[object ' + type + ']';
  5. }
  6. }
  7. var isString = isType(“String”);
  8. var isObject = isType("Object");
  9. var isArray = isType("Array");
  10. isString("I'm Barret Lee.");
  11. isArray([1,2,3]);
  12. isObject({});

  10.jquery里的去除空格trim妙用

 

  1. //相当于if (String.prototype.trim && “\uFEFF\xA0″.trim() !== “”)高级的浏览器已经支持原生的String的trim方法,但是pFan还为了避免它没法解析全角空白,所以加多了一个判断:”\uFEFF\xA0″.trim() !== “”
  2. vart core_version = "1.0",core_trim = core_version.trim;
  3. function trim(){
  4. core_trim && !core_trim.call("\uFEFF\xA0") ?
  5. function (text) {
  6. return text == null ?
  7. "" :
  8. core_trim.call(text); //这里按我的理解应该为" ".trim.call(text),有点不明白转换为"1.1.0".trim.call(text)
  9. } :
  10. // 高级的浏览器已经支持原生的String的trim方法,如果浏览器不支持则采用
  11. function (text) {
  12. var whitespace = "[\\x20\\t\\r\\n\\f]",
  13. rtrim = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g");
  14. return text == null ?
  15. "" :
  16. (text + "").replace(rtrim, "");
  17. },
  18. //nodeName函数是获取dom节点的节点名字或者判断其名字跟传入参数是否匹配
  19. nodeName: function(elem,name){
  20. //IE下,DOM节点的nodeName是大写的,例如DIV
  21. return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
  22. }
  23. }

  11.jquery中检测数组或者类数组中是否含存在传入的值

  1. /**
  2. 检查数组中是否存在传入的值,如果存在就返回值所在的位置,如果不存在就返回-1。
  3. *elem 规定需检索的值。
  4. *arr 数组
  5. *i 可选的整数参数。规定在数组中开始检索的位置。它的合法取值是 0 到 arr.length - 1。如省略该参数,则将从数组首元素开始检索。
  6. */
  7. function inArray(elem, arr, i){
  8. var len;
  9. if (arr) {
  10. //如果浏览器支持Array拥有indexOf方法
  11. if ([].indexOf) {
  12. return [].indexOf.call(arr, elem, i);
  13. }
  14. len = arr.length;
  15. //当i为负数的时候,从数组后边len+i的位置开始索引
  16. //理解这个分成两个部分i = i ? (i < 0 ? Math.max(0, len + i) : i) : 0;,i=i为true,执行(i < 0 ? Math.max(0, len + i) : i),反正执行i=0
  17. i = i ? i < 0 ? Math.max(0, len + i) : i : 0;
  18. for (; i < len; i++) {
  19. // 双重检测防止类似这样的数组 ar = [];ar[1]=1;ar[0] = undefined; 0 in ar =false;a[0]===undefined;
  20. // 0 in arr => arr[0]是否存在 'nme' in arr => arr['nme']是否存在
  21. if (i in arr && arr[i] === elem) {
  22. return i;
  23. }
  24. }
  25. }
  26. return -1;
  27. }

 

二、javascript中原型链常见的知识点

  1.hasOwnProperty()方法

   使用hasOwnProperty()方法可以检测一个属性是存在与实例,还是存在于原型中。这个方法从Object继承,只在给定属性存在于对象实例中时,才会返回true。

  1. function Person(){
  2. this.age=25;
  3. this.job="web";
  4. }
  5. Person.prototype={
  6. name:'pingfan',
  7. sayName:function(){
  8. alert(this.name);
  9. }
  10. }
  11. var person1=new Person();
  12. //来自构造函数,检测属性,也返回true
  13. alert(person1.hasOwnProperty("age"));
  14. //来自原型属性,返回false
  15. alert(person1.hasOwnProperty("name"));
  16. person1.name='ping';
  17. //来自实例属性,返回true
  18. alert(person1.hasOwnProperty("name"));

  2.通过instanceOf检查this是否为构造函数的一个实例

  1. function shiCha(opt){
  2. //检测this是否为对象的实例
  3. if( !(this instanceof shiCha)){
  4. return new shiCha(opt);
  5. }
  6. }
  7. var shicha1 = new shiCha(), //会返回一个shiCha对象
       shicha2 = shiCha(); //构造函数作为函数时与其他函数无意,this指向window

  3.javascript中Array.prototype.slice.call(arguments)  

  我们通常看到Array.prototype.slice.call(arguments,1)或者Array.prototype.slice.call(arguments),都有点摸不着头脑,其实我们就是借助Array.prototype中slice()将arguments变成一个数组,并且使用该数组工作更方便,第二个参数是从索引值,开始将其变成数组,例Array.prototype.call("22223",2)和Array.prototype.call([1,2,3,4],2),从字符串第二个开始。

  1. function sliArray(array){
  2. //输出为从索引1到索引3
  3. return Array.prototype.slice.call(array,1,3);
  4. }
  5. alert(sliArray([1,2,3,4,5,6])) //结果为2,3

  4.利用闭包,实现单例模式,保证构造函数只实例一次

  1. //对象之间永远不会完全相等,除非它们是同一对象,因此即使创建一个具有完全相同成员的同类对象,它也不会与第一个对象完全相同
         var Universe;
  2. (function(){
  3. var instance;
  4. Universe = function Universe(){
  5. if(instance){
  6. return instance;
  7. }
  8. instance = this;
  9. //所有功能
  10. this.start_time = 0;
  11. this.bang = "Big";
  12. }
  13. })()
  14. var person1 = new Universe(),
  15. person2 = new Universe();
  16. alert(person1 === person2 ); //返回true

  5. 利用空对象F,实现对象继承,效率最高

  1. //利用空对象做媒介,进行继承效果最佳
  2. function inhert(C,P){
  3. var F=function(){};
  4. F.protototype = P.prototype;
  5. C.prototype = new F();
  6. C.prototype.constructor = C;
  7. }

  6. 构造函数设置return obj对象,会导致对象与原型链断掉

  理解这个问题,先理解一个概念,通常我们用new Object(),其实可以理解为隐式的做了三件事情:

    ①.创建一个空对象,var this ={},继承object对象的一些原有的属性;
    ②.将构造函数写的属性挂载到创建的对象,this.name = "pfan";
    ③.通过new object(),返回this对象
   场景一

  1. var Parent = function (){
  2. var that = {};
  3. that.name = "pfan";
  4. that.age = "25";
  5. return that;
  6. }
  7. Parent.prototype = {
  8. contructor:"Parent",
  9. sayName:function(){
  10. alert(this.name);
  11. },
  12. sayAge:function(){
  13. alert(this.age);
  14. }
  15. }
  16. var child = Parent(),
  17. last = new Parent();
  18. console.dir(child);
  19. console.dir(last);
  20. child.sayName();
  21. last.sayName();

  我们执行打开chrome控制台,发现通过Parent(),new Parent()方法生成的对象原型链都断裂了。

  场景二:我们把对象的属性挂载在this上,也达不到想要的结果,构造函数如下:

  1. var Parent = function (){
  2. var that = {};
  3. this.name = "pfan";
  4. this.age = "25";
  5. return that;
  6. }

  chrome控制台结果:

  场景三:我们更大胆一点,直接让that成一个对象,返回that,观察new Parent(),出来的对象,是否拥有prototype上的方法

  1. var Parent = function (){
  2. this.name = "pfan";
  3. this.age = "25";
  4. var that = {name:"pfan111",age:"2511"}
  5. return that;
  6. }

  chrome控制台,可以看到new Parent(),实例返回的对象构造函数设置的返回对象,没有继承原型的prototype方法

  

  思考??:如果构造函数返回Array,null,通过new 实例会出现什么情况呢?

  1.Array,返回了一个Array对象,无法继承prototype的原型

  

  2.null结果是返回继承原型链的对象

  场景四:构造函数中不返回对象,返回字符串

  1. var Parent = function (){
  2. this.name = "pfan";
  3. this.age = "25";
  4. return "11111";
  5. }

  chrome控制台:发现出来的结果,继承了原型链

  通过以上四个场景,我们得出结论:

    1.构造函数里面,我们设置return 返回对象或者数组,通过new实例时,会导致原型链断裂

    2.构造函数里面,我们设置return 返回字符串或者null,或者alert(),通过new实例时,会直接忽略

三、javascript中常用方法集

  1. 常见的数组操作方法

  数组去重:

  1. //数组去重原型
  2. Array.prototype.unqie = function(){
  3. var arr = this, len=this.length, obj={}, newArr=[];
  4. while(len--){
  5. if(obj[ arr[len] ] !== arr[len]){
  6. obj[arr[len]] = arr[len]; newArr.push( arr[len]);
  7. }
  8. }
  9. return newArr.reverse();
  10. }
    //也可以通过变量来记录匹配,效率更高

Array.prototype.unique = function(){
  var arr = this,poxy,i = arr.length,newArr=[];
  while(i--){
    if(poxy != arr[i]){
      poxy = arr[i];
      newArr.push(arr[i]);
    }
  }
  return newArr.reverse();
}

  1.  

  取数组中最大值:

  1. Array.prototype.arrMax=function(){
  2. var arr=this, len=this.length,max=arr[0];
  3. for(var i=1;i<len;i++){
  4. if(max<arr[i]){
  5. max=arr[i];
  6. }
  7. }
  8. return max;
  9. }
  10. //数组中通过sort取最大值
  11.   Array.prototype.arrMax=function(){
  12.     var arr=this;
  13.     arr.sort(function(a,b){
  14.       return a-b;
  15.     })
  16.     return arr[arr.length-1];
  17.   }
  18. //利用Math.max取数组最大值
  19. Array.prototype.arrMax =function(){
  20. var array = this;
  21. return Math.max.apply(null, array);
  22. }
  23. alert([1,2,3,4,5,6,9,8,7,9].arrMax());

  取数组中最小值:

  1. //数组中最的小值
  2. Array.prototype.arrMin=function(){
  3. var arr=this, len=this.length,min=arr[0];
  4. for(var i=1;i<len;i++){
  5. if(min>arr[i]){
  6. min=arr[i];
  7. }
  8. }
  9. return min;
  10. }
  11. //数组中通过sort取最的小值
  12. Array.prototype.arrSortMin=function(){
  13.     var arr=this;
  14.     arr.sort(function(a,b){
  15.       return a-b;
  16.     })
  17.     return arr[0];
  18. }
  19. //利用Math.max取数组最大值
  20. Array.prototype.arrSortMin =function(){
  21. var array = this;
  22. return Math.min.apply(null, array);
  23. }
  24. alert([1,2,3,4,5,6,9,8,7,9].arrSortMin());

  复制数组:

  1. Array.prototype.copy =
  2. function() {
  3. return [].concat(this);
  4. };

  去除数组中只指定元素,只能去除一个,如果想多个,之前先用unique处理:

  1. Array.prototype.remove = function(value){
  2. for(var i=0,len=this.length;i<len;i++)
  3. {
  4. if(this[i]==value){
  5. this.splice(i, 1);
  6. break;
  7. }
  8. }
  9. return this;
  10. }

  判断数组中元素出现的次数最多的一个元素和次数: 

  1. Array.prototype.maxNum = function(){
  2. var arr = this,obj={};
  3. for(var i =0, len=arr.length;i<len;i++){
  4. var key = arr[i];
  5. if( ! obj[key]){
  6. obj[key] = 1;
  7. }else{
  8. obj[key]++;
  9. }
  10. }
  11. var max = -1,maxStr;
  12. for( key in obj){
  13. if(obj[key]>max){
  14. max = obj[key];
  15. maxStr = key;
  16. }
  17. }
  18. //alert(maxStr); maxStr为最大的元素,max为次数
  19. return [maxStr,max];
  20. }

 

  2.操作document.loaction的方法集(这里借用了园友总结的相关方法)

  1. pFan.url = { //#URL
  2. //参数:变量名,url为空则表从当前页面的url中取
  3. getQuery: function (name, url) {
  4. var u = arguments[1] || window.location.search
  5. , reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)")
  6. , r = u.substr(u.indexOf("?") + 1).match(reg)
  7. ;
  8. return r != null ? r[2] : "";
  9. }
  10. , getHash: function (name, url) { //# 获取 hash值
  11. var u = arguments[1] || location.hash;
  12. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  13. var r = u.substr(u.indexOf("#") + 1).match(reg);
  14. if (r != null) {
  15. return r[2];
  16. }
  17. return "";
  18. }
  19. , parse: function (url) { //# 解析URL
  20. var a = document.createElement('a');
  21. url = url || document.location.href;
  22. a.href = url;
  23. return {
  24. source: url
  25. , protocol: a.protocol.replace(':', '')
  26. , host: a.hostname
  27. , port: a.port
  28. , query: a.search
  29. , file: (a.pathname.match(/([^\/?#]+)$/i) || [, ''])[1]
  30. , hash: a.hash.replace('#', '')
  31. , path: a.pathname.replace(/^([^\/])/, '/$1')
  32. , relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1]
  33. , segments: a.pathname.replace(/^\//, '').split('/')
  34. };
  35. }
  36. };

  3.常用的正则表达式

  1. pFan.regExp = { //# 字符串匹配
  2. //是否为 数字!整数,浮点数
  3. isNum: function (num) { //# 是否为数组
  4. return !isNaN(num);
  5. }
  6. , isEmail: function (mail) {//# 是否为 邮箱
  7. return /^([a-z0-9]+[_\-\.]?)*[a-z0-9]+@([a-z0-9]+[_\-\.]?)*[a-z0-9]+\.[a-z]{2,5}$/i.test(mail);
  8. }
  9. , isIdCard: function (card) { //# 是否为 身份证
  10. return /^(\d{14}|\d{17})(\d|[xX])$/.test(card);
  11. }
  12. , isMobile: function (mobile) { //# 是否为 手机
  13. return /^0*1\d{10}$/.test(mobile);
  14. }
  15. , isQQ: function (qq) { //# 是否为 QQ
  16. return /^[1-9]\d{4,10}$/.test(qq);
  17. }
  18. , isTel: function (tel) { //# 是否为 电话
  19. return /^\d{3,4}-\d{7,8}(-\d{1,6})?$/.text(tel);
  20. }
  21. , isUrl: function (url) { //# 是否为 URL
  22. return /https?:\/\/[a-z0-9\.\-]{1,255}\.[0-9a-z\-]{1,255}/i.test(url);
  23. }
  24. , isColor: function (color) { //# 是否为 16进制颜色
  25. return /#([\da-f]{3}){1,2}$/i.test(color);
  26. }
  27. //@id : 身份证 ,
  28. // @now : 当前时间 如:new Date('2013/12/12') , '2013/12/12'
  29. // @age : 允许的年龄
  30. , isAdult: function (id, allowAge, now) { //# 是否年龄是否成年
  31. var age = 0 // 用户 年月日
  32. , nowDate = 0 //当前年月日
  33. ;
  34. allowAge = parseFloat(allowAge) || 18;
  35. now = typeof now == 'string' ? new Date(now) : (now || new Date());
  36. if (!this.isIdCard(id)) {
  37. return false;
  38. }
  39. //15位身份证
  40. if (15 == id.length) {
  41. age = '19' + id.slice(6, 6);
  42. } else {
  43. age = id.slice(6, 14);
  44. }
  45. // 类型转换 整型
  46. age = ~~age;
  47. nowDate = ~~(Tydic.date.format('YYYYMMDD', now));
  48. //比较年龄
  49. if (nowDate - age < allowAge * 1e4) {
  50. return false;
  51. }
  52. return true;
  53. }
  54. //浮点数
  55. , isFloat: function (num) { //# 是否为 浮点数
  56. return /^(([1-9]\d*)|(\d+\.\d+)|0)$/.test(num);
  57. }
  58. //正整数
  59. , isInt: function (num) { //# 是否为 正整数
  60. return /^[1-9]\d*$/.test(num);
  61. }
  62. //是否全为汉字
  63. , isChinese: function (str) { //# 是否全为 汉字
  64. return /^([\u4E00-\u9FA5]|[\uFE30-\uFFA0])+$/gi.test(str);
  65. }
  66. };

  4.操作className的方法集

  1. PFan.conClass = {
  2. hasClass:function(){
  3. return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
  4. },
  5. addClass:function(){
  6. if (!hasClass(ele,cls)) ele.className += " "+cls;
  7. },
  8. removeClass:function(){
  9. if (hasClass(ele,cls)) {
  10. var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
  11. ele.className=ele.className.replace(reg,' ');
  12. }
  13. }
  14. }

  5.操作字符串方法

  1. pFan.string = { //# 字符串
  2. codeHtml: function (content) { //# 转义 HTML 字符
  3. return this.replace(content, {
  4. '&': "&amp;"
  5. , '"': "&quot;"
  6. , "'": '&#39;'
  7. , '<': "&lt;"
  8. , '>': "&gt;"
  9. , ' ': "&nbsp;"
  10. , '\t': "&#09;"
  11. , '(': "&#40;"
  12. , ')': "&#41;"
  13. , '*': "&#42;"
  14. , '+': "&#43;"
  15. , ',': "&#44;"
  16. , '-': "&#45;"
  17. , '.': "&#46;"
  18. , '/': "&#47;"
  19. , '?': "&#63;"
  20. , '\\': "&#92;"
  21. , '\n': "<br>"
  22. });
  23. }
  24. //重复字符串
  25. , repeat: function (word, length, end) { //# 重复字符串
  26. end = end || ''; //加在末位
  27. length = ~~length;
  28. return new Array(length * 1 + 1).join(word) + '' + end;
  29. }
  30. //增加前缀
  31. , addPre: function (pre, word, size) { //# 补齐。如给数字前 加 0
  32. pre = pre || '0';
  33. size = parseInt(size) || 0;
  34. word = String(word || '');
  35. var length = Math.max(0, size - word.length);
  36. return this.repeat(pre, length, word);
  37. }
  38. //去除两边空格
  39. , trim: function (text) { //# 去除两边空格
  40. return (text || '').replace(/^\s+|\s$/, '');
  41. }
  42. //去除左边空格
  43. ,ltrim:function(){
  44. return s.replace( /^(\s*| *)/, "");
  45. }
  46. //去除右边空格
  47. ,rtrim:function(){
  48. return s.replace( /(\s*| *)$/, "");
  49. }
  50. //返回脚本内容
  51. ,evalscript:function(s) {
  52. if(s.indexOf('<script') == -1) return s;
  53. var p = /<script[^\>]*?>([^\x00]*?)<\/script>/ig;
  54. var arr = [];
  55. while(arr = p.exec(s)) {
  56. var p1 = /<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/i;
  57. var arr1 = [];
  58. arr1 = p1.exec(arr[0]);
  59. if(arr1) {
  60. appendscript(arr1[1], '', arr1[2], arr1[3]);
  61. } else {
  62. p1 = /<script(.*?)>([^\x00]+?)<\/script>/i;
  63. arr1 = p1.exec(arr[0]);
  64. appendscript('', arr1[2], arr1[1].indexOf('reload=') != -1);
  65. }
  66. }
  67. return s;
  68. }
  69. //清除脚本内容
  70. ,stripscript:function(){
  71. return s.replace(/<script.*?>.*?<\/script>/ig, '');
  72. }
  73. //字符串替换
  74. , replace: function (str, re) { //# 字符串替换
  75. str = str || '';
  76. for (var key in re) {
  77. replace(key, re[key]);
  78. };
  79. function replace(a, b) {
  80. var arr = str.split(a);
  81. str = arr.join(b);
  82. };
  83. return str;
  84. }
  85. , xss: function (str, type) { //# XSS 转义
  86. //空过滤
  87. if (!str) {
  88. return str === 0 ? "0" : "";
  89. }
  90. switch (type) {
  91. case "html": //过滤html字符串中的XSS
  92. return str.replace(/[&'"<>\/\\\-\x00-\x09\x0b-\x0c\x1f\x80-\xff]/g, function (r) {
  93. return "&#" + r.charCodeAt(0) + ";"
  94. }).replace(/ /g, "&nbsp;").replace(/\r\n/g, "<br />").replace(/\n/g, "<br />").replace(/\r/g, "<br />");
  95. break;
  96. case "htmlEp": //过滤DOM节点属性中的XSS
  97. return str.replace(/[&'"<>\/\\\-\x00-\x1f\x80-\xff]/g, function (r) {
  98. return "&#" + r.charCodeAt(0) + ";"
  99. });
  100. break;
  101. case "url": //过滤url
  102. return escape(str).replace(/\+/g, "%2B");
  103. break;
  104. case "miniUrl":
  105. return str.replace(/%/g, "%25");
  106. break;
  107. case "script":
  108. return str.replace(/[\\"']/g, function (r) {
  109. return "\\" + r;
  110. }).replace(/%/g, "\\x25").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\x01/g, "\\x01");
  111. break;
  112. case "reg":
  113. return str.replace(/[\\\^\$\*\+\?\{\}\.\(\)\[\]]/g, function (a) {
  114. return "\\" + a;
  115. });
  116. break;
  117. default:
  118. return escape(str).replace(/[&'"<>\/\\\-\x00-\x09\x0b-\x0c\x1f\x80-\xff]/g, function (r) {
  119. return "&#" + r.charCodeAt(0) + ";"
  120. }).replace(/ /g, "&nbsp;").replace(/\r\n/g, "<br />").replace(/\n/g, "<br />").replace(/\r/g, "<br />");
  121. break;
  122. }
  123. }
  124. // badword , 过滤敏感词
  125. //@text : 要过滤的文本 , 类型 :字符串
  126. //@words : 敏感词 ,类型,数组, 如 : ['你妹', '我丢' ,'我靠']
  127. // 如果 用 正则匹配, text 长度 100万,words 100万,需要 4秒!
  128. , badWord: function (text, words) { //# 敏感词过滤
  129. text = String(text || '');
  130. words = words || [];
  131. var reg = new RegExp(words.join('|'), 'g')
  132. , _self = this;
  133. return text.replace(reg, function ($0) {
  134. var length = String($0 || '').length;
  135. return _self.repeat('*', length);
  136. });
  137. }
  138. };

  6.加密方法集

  1. pFan.encrypt = { //# 加密
  2. md5: function (words) { //# md5 哈希算法
  3. /*
  4. * Crypto-JS 3.1.2
  5. * http://code.google.com/p/crypto-js
  6. */
  7. var CryptoJS = function (s, p) {
  8. var m = {}, l = m.lib = {}, n = function () { }, r = l.Base = { extend: function (b) { n.prototype = this; var h = new n; b && h.mixIn(b); h.hasOwnProperty("init") || (h.init = function () { h.$super.init.apply(this, arguments) }); h.init.prototype = h; h.$super = this; return h }, create: function () { var b = this.extend(); b.init.apply(b, arguments); return b }, init: function () { }, mixIn: function (b) { for (var h in b) b.hasOwnProperty(h) && (this[h] = b[h]); b.hasOwnProperty("toString") && (this.toString = b.toString) }, clone: function () { return this.init.prototype.extend(this) } }, q = l.WordArray = r.extend({ init: function (b, h) { b = this.words = b || []; this.sigBytes = h != p ? h : 4 * b.length }, toString: function (b) { return (b || t).stringify(this) }, concat: function (b) { var h = this.words, a = b.words, j = this.sigBytes; b = b.sigBytes; this.clamp(); if (j % 4) for (var g = 0; g < b; g++) h[j + g >>> 2] |= (a[g >>> 2] >>> 24 - 8 * (g % 4) & 255) << 24 - 8 * ((j + g) % 4); else if (65535 < a.length) for (g = 0; g < b; g += 4) h[j + g >>> 2] = a[g >>> 2]; else h.push.apply(h, a); this.sigBytes += b; return this }, clamp: function () { var b = this.words, h = this.sigBytes; b[h >>> 2] &= 4294967295 << 32 - 8 * (h % 4); b.length = s.ceil(h / 4) }, clone: function () { var b = r.clone.call(this); b.words = this.words.slice(0); return b }, random: function (b) { for (var h = [], a = 0; a < b; a += 4) h.push(4294967296 * s.random() | 0); return new q.init(h, b) } }), v = m.enc = {}, t = v.Hex = { stringify: function (b) { var a = b.words; b = b.sigBytes; for (var g = [], j = 0; j < b; j++) { var k = a[j >>> 2] >>> 24 - 8 * (j % 4) & 255; g.push((k >>> 4).toString(16)); g.push((k & 15).toString(16)) } return g.join("") }, parse: function (b) { for (var a = b.length, g = [], j = 0; j < a; j += 2) g[j >>> 3] |= parseInt(b.substr(j, 2), 16) << 24 - 4 * (j % 8); return new q.init(g, a / 2) } }, a = v.Latin1 = { stringify: function (b) { var a = b.words; b = b.sigBytes; for (var g = [], j = 0; j < b; j++) g.push(String.fromCharCode(a[j >>> 2] >>> 24 - 8 * (j % 4) & 255)); return g.join("") }, parse: function (b) { for (var a = b.length, g = [], j = 0; j < a; j++) g[j >>> 2] |= (b.charCodeAt(j) & 255) << 24 - 8 * (j % 4); return new q.init(g, a) } }, u = v.Utf8 = { stringify: function (b) { try { return decodeURIComponent(escape(a.stringify(b))) } catch (g) { throw Error("Malformed UTF-8 data"); } }, parse: function (b) { return a.parse(unescape(encodeURIComponent(b))) } },
  9. g = l.BufferedBlockAlgorithm = r.extend({ reset: function () { this._data = new q.init; this._nDataBytes = 0 }, _append: function (b) { "string" == typeof b && (b = u.parse(b)); this._data.concat(b); this._nDataBytes += b.sigBytes }, _process: function (b) { var a = this._data, g = a.words, j = a.sigBytes, k = this.blockSize, m = j / (4 * k), m = b ? s.ceil(m) : s.max((m | 0) - this._minBufferSize, 0); b = m * k; j = s.min(4 * b, j); if (b) { for (var l = 0; l < b; l += k) this._doProcessBlock(g, l); l = g.splice(0, b); a.sigBytes -= j } return new q.init(l, j) }, clone: function () { var b = r.clone.call(this); b._data = this._data.clone(); return b }, _minBufferSize: 0 }); l.Hasher = g.extend({ cfg: r.extend(), init: function (b) { this.cfg = this.cfg.extend(b); this.reset() }, reset: function () { g.reset.call(this); this._doReset() }, update: function (b) { this._append(b); this._process(); return this }, finalize: function (b) { b && this._append(b); return this._doFinalize() }, blockSize: 16, _createHelper: function (b) { return function (a, g) { return (new b.init(g)).finalize(a) } }, _createHmacHelper: function (b) { return function (a, g) { return (new k.HMAC.init(b, g)).finalize(a) } } }); var k = m.algo = {}; return m
  10. }(Math);
  11. (function (s) {
  12. function p(a, k, b, h, l, j, m) { a = a + (k & b | ~k & h) + l + m; return (a << j | a >>> 32 - j) + k } function m(a, k, b, h, l, j, m) { a = a + (k & h | b & ~h) + l + m; return (a << j | a >>> 32 - j) + k } function l(a, k, b, h, l, j, m) { a = a + (k ^ b ^ h) + l + m; return (a << j | a >>> 32 - j) + k } function n(a, k, b, h, l, j, m) { a = a + (b ^ (k | ~h)) + l + m; return (a << j | a >>> 32 - j) + k } for (var r = CryptoJS, q = r.lib, v = q.WordArray, t = q.Hasher, q = r.algo, a = [], u = 0; 64 > u; u++) a[u] = 4294967296 * s.abs(s.sin(u + 1)) | 0; q = q.MD5 = t.extend({
  13. _doReset: function () { this._hash = new v.init([1732584193, 4023233417, 2562383102, 271733878]) }, _doProcessBlock: function (g, k) {
  14. for (var b = 0; 16 > b; b++) { var h = k + b, w = g[h]; g[h] = (w << 8 | w >>> 24) & 16711935 | (w << 24 | w >>> 8) & 4278255360 } var b = this._hash.words, h = g[k + 0], w = g[k + 1], j = g[k + 2], q = g[k + 3], r = g[k + 4], s = g[k + 5], t = g[k + 6], u = g[k + 7], v = g[k + 8], x = g[k + 9], y = g[k + 10], z = g[k + 11], A = g[k + 12], B = g[k + 13], C = g[k + 14], D = g[k + 15], c = b[0], d = b[1], e = b[2], f = b[3], c = p(c, d, e, f, h, 7, a[0]), f = p(f, c, d, e, w, 12, a[1]), e = p(e, f, c, d, j, 17, a[2]), d = p(d, e, f, c, q, 22, a[3]), c = p(c, d, e, f, r, 7, a[4]), f = p(f, c, d, e, s, 12, a[5]), e = p(e, f, c, d, t, 17, a[6]), d = p(d, e, f, c, u, 22, a[7]), c = p(c, d, e, f, v, 7, a[8]), f = p(f, c, d, e, x, 12, a[9]), e = p(e, f, c, d, y, 17, a[10]), d = p(d, e, f, c, z, 22, a[11]), c = p(c, d, e, f, A, 7, a[12]), f = p(f, c, d, e, B, 12, a[13]), e = p(e, f, c, d, C, 17, a[14]), d = p(d, e, f, c, D, 22, a[15]), c = m(c, d, e, f, w, 5, a[16]), f = m(f, c, d, e, t, 9, a[17]), e = m(e, f, c, d, z, 14, a[18]), d = m(d, e, f, c, h, 20, a[19]), c = m(c, d, e, f, s, 5, a[20]), f = m(f, c, d, e, y, 9, a[21]), e = m(e, f, c, d, D, 14, a[22]), d = m(d, e, f, c, r, 20, a[23]), c = m(c, d, e, f, x, 5, a[24]), f = m(f, c, d, e, C, 9, a[25]), e = m(e, f, c, d, q, 14, a[26]), d = m(d, e, f, c, v, 20, a[27]), c = m(c, d, e, f, B, 5, a[28]), f = m(f, c, d, e, j, 9, a[29]), e = m(e, f, c, d, u, 14, a[30]), d = m(d, e, f, c, A, 20, a[31]), c = l(c, d, e, f, s, 4, a[32]), f = l(f, c, d, e, v, 11, a[33]), e = l(e, f, c, d, z, 16, a[34]), d = l(d, e, f, c, C, 23, a[35]), c = l(c, d, e, f, w, 4, a[36]), f = l(f, c, d, e, r, 11, a[37]), e = l(e, f, c, d, u, 16, a[38]), d = l(d, e, f, c, y, 23, a[39]), c = l(c, d, e, f, B, 4, a[40]), f = l(f, c, d, e, h, 11, a[41]), e = l(e, f, c, d, q, 16, a[42]), d = l(d, e, f, c, t, 23, a[43]), c = l(c, d, e, f, x, 4, a[44]), f = l(f, c, d, e, A, 11, a[45]), e = l(e, f, c, d, D, 16, a[46]), d = l(d, e, f, c, j, 23, a[47]), c = n(c, d, e, f, h, 6, a[48]), f = n(f, c, d, e, u, 10, a[49]), e = n(e, f, c, d,
  15. C, 15, a[50]), d = n(d, e, f, c, s, 21, a[51]), c = n(c, d, e, f, A, 6, a[52]), f = n(f, c, d, e, q, 10, a[53]), e = n(e, f, c, d, y, 15, a[54]), d = n(d, e, f, c, w, 21, a[55]), c = n(c, d, e, f, v, 6, a[56]), f = n(f, c, d, e, D, 10, a[57]), e = n(e, f, c, d, t, 15, a[58]), d = n(d, e, f, c, B, 21, a[59]), c = n(c, d, e, f, r, 6, a[60]), f = n(f, c, d, e, z, 10, a[61]), e = n(e, f, c, d, j, 15, a[62]), d = n(d, e, f, c, x, 21, a[63]); b[0] = b[0] + c | 0; b[1] = b[1] + d | 0; b[2] = b[2] + e | 0; b[3] = b[3] + f | 0
  16. }, _doFinalize: function () { var a = this._data, k = a.words, b = 8 * this._nDataBytes, h = 8 * a.sigBytes; k[h >>> 5] |= 128 << 24 - h % 32; var l = s.floor(b / 4294967296); k[(h + 64 >>> 9 << 4) + 15] = (l << 8 | l >>> 24) & 16711935 | (l << 24 | l >>> 8) & 4278255360; k[(h + 64 >>> 9 << 4) + 14] = (b << 8 | b >>> 24) & 16711935 | (b << 24 | b >>> 8) & 4278255360; a.sigBytes = 4 * (k.length + 1); this._process(); a = this._hash; k = a.words; for (b = 0; 4 > b; b++) h = k[b], k[b] = (h << 8 | h >>> 24) & 16711935 | (h << 24 | h >>> 8) & 4278255360; return a }, clone: function () { var a = t.clone.call(this); a._hash = this._hash.clone(); return a }
  17. }); r.MD5 = t._createHelper(q); r.HmacMD5 = t._createHmacHelper(q)
  18. })(Math);
  19. return CryptoJS.MD5(words).toString();
  20. }
  21. // sha1
  22. , sha1: function (words) { //# sha1 哈希算法
  23. var CryptoJS = function (e, m) { var p = {}, j = p.lib = {}, l = function () { }, f = j.Base = { extend: function (a) { l.prototype = this; var c = new l; a && c.mixIn(a); c.hasOwnProperty("init") || (c.init = function () { c.$super.init.apply(this, arguments) }); c.init.prototype = c; c.$super = this; return c }, create: function () { var a = this.extend(); a.init.apply(a, arguments); return a }, init: function () { }, mixIn: function (a) { for (var c in a) a.hasOwnProperty(c) && (this[c] = a[c]); a.hasOwnProperty("toString") && (this.toString = a.toString) }, clone: function () { return this.init.prototype.extend(this) } }, n = j.WordArray = f.extend({ init: function (a, c) { a = this.words = a || []; this.sigBytes = c != m ? c : 4 * a.length }, toString: function (a) { return (a || h).stringify(this) }, concat: function (a) { var c = this.words, q = a.words, d = this.sigBytes; a = a.sigBytes; this.clamp(); if (d % 4) for (var b = 0; b < a; b++) c[d + b >>> 2] |= (q[b >>> 2] >>> 24 - 8 * (b % 4) & 255) << 24 - 8 * ((d + b) % 4); else if (65535 < q.length) for (b = 0; b < a; b += 4) c[d + b >>> 2] = q[b >>> 2]; else c.push.apply(c, q); this.sigBytes += a; return this }, clamp: function () { var a = this.words, c = this.sigBytes; a[c >>> 2] &= 4294967295 << 32 - 8 * (c % 4); a.length = e.ceil(c / 4) }, clone: function () { var a = f.clone.call(this); a.words = this.words.slice(0); return a }, random: function (a) { for (var c = [], b = 0; b < a; b += 4) c.push(4294967296 * e.random() | 0); return new n.init(c, a) } }), b = p.enc = {}, h = b.Hex = { stringify: function (a) { var c = a.words; a = a.sigBytes; for (var b = [], d = 0; d < a; d++) { var f = c[d >>> 2] >>> 24 - 8 * (d % 4) & 255; b.push((f >>> 4).toString(16)); b.push((f & 15).toString(16)) } return b.join("") }, parse: function (a) { for (var c = a.length, b = [], d = 0; d < c; d += 2) b[d >>> 3] |= parseInt(a.substr(d, 2), 16) << 24 - 4 * (d % 8); return new n.init(b, c / 2) } }, g = b.Latin1 = { stringify: function (a) { var c = a.words; a = a.sigBytes; for (var b = [], d = 0; d < a; d++) b.push(String.fromCharCode(c[d >>> 2] >>> 24 - 8 * (d % 4) & 255)); return b.join("") }, parse: function (a) { for (var c = a.length, b = [], d = 0; d < c; d++) b[d >>> 2] |= (a.charCodeAt(d) & 255) << 24 - 8 * (d % 4); return new n.init(b, c) } }, r = b.Utf8 = { stringify: function (a) { try { return decodeURIComponent(escape(g.stringify(a))) } catch (c) { throw Error("Malformed UTF-8 data"); } }, parse: function (a) { return g.parse(unescape(encodeURIComponent(a))) } }, k = j.BufferedBlockAlgorithm = f.extend({ reset: function () { this._data = new n.init; this._nDataBytes = 0 }, _append: function (a) { "string" == typeof a && (a = r.parse(a)); this._data.concat(a); this._nDataBytes += a.sigBytes }, _process: function (a) { var c = this._data, b = c.words, d = c.sigBytes, f = this.blockSize, h = d / (4 * f), h = a ? e.ceil(h) : e.max((h | 0) - this._minBufferSize, 0); a = h * f; d = e.min(4 * a, d); if (a) { for (var g = 0; g < a; g += f) this._doProcessBlock(b, g); g = b.splice(0, a); c.sigBytes -= d } return new n.init(g, d) }, clone: function () { var a = f.clone.call(this); a._data = this._data.clone(); return a }, _minBufferSize: 0 }); j.Hasher = k.extend({ cfg: f.extend(), init: function (a) { this.cfg = this.cfg.extend(a); this.reset() }, reset: function () { k.reset.call(this); this._doReset() }, update: function (a) { this._append(a); this._process(); return this }, finalize: function (a) { a && this._append(a); return this._doFinalize() }, blockSize: 16, _createHelper: function (a) { return function (c, b) { return (new a.init(b)).finalize(c) } }, _createHmacHelper: function (a) { return function (b, f) { return (new s.HMAC.init(a, f)).finalize(b) } } }); var s = p.algo = {}; return p }(Math);
  24. (function () { var e = CryptoJS, m = e.lib, p = m.WordArray, j = m.Hasher, l = [], m = e.algo.SHA1 = j.extend({ _doReset: function () { this._hash = new p.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520]) }, _doProcessBlock: function (f, n) { for (var b = this._hash.words, h = b[0], g = b[1], e = b[2], k = b[3], j = b[4], a = 0; 80 > a; a++) { if (16 > a) l[a] = f[n + a] | 0; else { var c = l[a - 3] ^ l[a - 8] ^ l[a - 14] ^ l[a - 16]; l[a] = c << 1 | c >>> 31 } c = (h << 5 | h >>> 27) + j + l[a]; c = 20 > a ? c + ((g & e | ~g & k) + 1518500249) : 40 > a ? c + ((g ^ e ^ k) + 1859775393) : 60 > a ? c + ((g & e | g & k | e & k) - 1894007588) : c + ((g ^ e ^ k) - 899497514); j = k; k = e; e = g << 30 | g >>> 2; g = h; h = c } b[0] = b[0] + h | 0; b[1] = b[1] + g | 0; b[2] = b[2] + e | 0; b[3] = b[3] + k | 0; b[4] = b[4] + j | 0 }, _doFinalize: function () { var f = this._data, e = f.words, b = 8 * this._nDataBytes, h = 8 * f.sigBytes; e[h >>> 5] |= 128 << 24 - h % 32; e[(h + 64 >>> 9 << 4) + 14] = Math.floor(b / 4294967296); e[(h + 64 >>> 9 << 4) + 15] = b; f.sigBytes = 4 * e.length; this._process(); return this._hash }, clone: function () { var e = j.clone.call(this); e._hash = this._hash.clone(); return e } }); e.SHA1 = j._createHelper(m); e.HmacSHA1 = j._createHmacHelper(m) })();
  25. return CryptoJS.SHA1(words).toString();
  26. }
  27. // time33 哈希
  28. , time33: function (words) { //# time33 哈希算法
  29. words = words || '';
  30. //哈希time33算法
  31. for (var i = 0, len = words.length, hash = 5381; i < len; ++i) {
  32. hash += (hash << 5) + words.charAt(i).charCodeAt();
  33. };
  34. return hash & 0x7fffffff;
  35. }
  36. }

  7.日期方法集

  1. pFan.date = {
  2. //返回时间戳
  3. getTimeStamp:function(){
  4. var timestamp=new Date().getTime();
  5. return timestamp.toString();
  6. },
  7. //时间戳转为日期格式
  8. //@nS为时间戳
  9. getLocalTime: function(nS) {
  10. return new Date(parseInt(nS) * 1000).toLocaleString().substr(0,17);
  11. },
  12. //@time , 时间 , 如 new Date('2013/11/10 0:12:12')
  13. //@pre , 星期的 前缀,如:周 ,星期
  14. //@ nums ,如:一二三四五六日
  15. getWeek: function (time, pre, nums) { //# 获取星期几
  16. time = typeof time == 'string' ? this.parse(time) : (time || new Date());
  17. pre = pre || '星期'; //
  18. nums = nums || '日一二三四五六';
  19. return pre + nums[time.getDay()];
  20. },
  21. //@formatType : YYYY, YY, MM
  22. //@ time : new Date('2013/11/12')
  23. //@weeks : 日一二三四五六
  24. format: function (formatType, time, weeks) { //格式化输出时间
  25. var pre = '0',
  26. formatType = formatType || 'YYYY-MM-DD',
  27. weeks = weeks || '日一二三四五六',
  28. time = time || new Date();
  29. //格式化时间
  30. return (formatType || '')
  31. .replace(/yyyy|YYYY/g, time.getFullYear())
  32. .replace(/yy|YY/g, Tydic.string.addPre(pre, time.getFullYear() % 100), 2)
  33. .replace(/mm|MM/g, Tydic.string.addPre(pre, time.getMonth() + 1, 2))
  34. .replace(/m|M/g, time.getMonth() + 1)
  35. .replace(/dd|DD/g, Tydic.string.addPre(pre, time.getDate(), 2))
  36. .replace(/d|D/g, time.getDate())
  37. .replace(/hh|HH/g, Tydic.string.addPre(pre, time.getHours(), 2))
  38. .replace(/h|H/g, time.getHours())
  39. .replace(/ii|II/g, Tydic.string.addPre(pre, time.getMinutes(), 2))
  40. .replace(/i|I/g, time.getMinutes())
  41. .replace(/ss|SS/g, Tydic.string.addPre(pre, time.getSeconds(), 2))
  42. .replace(/s|S/g, time.getSeconds())
  43. .replace(/w/g, time.getDay())
  44. .replace(/W/g, weeks[time.getDay()]);
  45. }
  46. }

 

四、经典实例应用

  1.递归方法实现如下数列:1,1,2,3,5,8,13,21,34,55……

  1. //a为位数 a为大于1的正整数
  2. function diGui(a){
  3. if(a<=2){
  4. return 1;
  5. }else{
  6. return arguments.callee(a-1)+arguments.callee(a-2);
  7. }
  8. }
  9. alert(diGui(31));

   2.百度产生时间戳的方法

  1. new Date()/36e5

   3.获取字符串字节,一个因为字母1个字节,一个中文字符2个字节

  1. //字节
  2. function getBite(str){
  3. var len = str.length,i=len;
  4. while(i--){
  5. //中文字符串的charCodeAt码大于255
  6. if(strrr[i].charCodeAt()>255)len++;
  7. }
  8. return len;
  9. }
  10. alert(getBite(strrr));

   4.var声明提前的问题

  1. var aa = 123;
  2. function alaa(){
  3. alert(aa) //结果为undefined
  4. var aa = "111"; //这里的声明被提前的,但是赋值在后
  5. alert(aa); //结果为111
  6. }
  7. alaa();

  等价于:

  1. var aa;
  2. alert(aa);
  3. aa=111;
  4. alert(aa);

   5.操作数组的问题

  1. var arr = [1,2,3,4,5,6];
  2. var newArr = arr;
  3. arr.splice(0,3);
  4. console.log(newArr); //弹出结果为[4,5,6] 
  1. newArr = arr,这一步其实我们像形成一种拷贝的形式,可是到我们去删除arr数组里面的而原始,发现newArr里面的元素也减少了,所以newArr = arr,只是将newArr的数组指针指向了arr,所以操作arr时影响newArr
    解决办法:
  1. var arr = [1,2,3,4,5,6];
  2. var newArr = arr.slice(0);
  3. arr.splice(0,3),arr.push("111");
  4. console.log(arr); //结果[4,5,6,"111"]
  5. console.log(newArr); //结果 [1,2,3,4,5,6]

   6.随机打乱数组

  1. function shuffle(array) {
  2. return array.sort(function() {
  3. return Math.random() - 0.5
  4. });
  5. }

 

 

    参考文字打乱数组顺序:http://www.cnblogs.com/wayou/p/fisher_yates_shuffle.html

  

  1.