Front-end JavaScript Knowledge (iii)

Source: Internet
Author: User
Tags object object

  • function memory, judgment is not prime.
    方法一:function isPrime1(n){    if(n<=3){return true}    else{      for(var i=2;i<Math.sqrt(n);i++){        if(n%i==0){return false;}      }      return true;    }};方法二:hash  var isPrime2=(function(){//hash    var hash={};    return function(n){      if(n<=3){return true}      else if(hash[n]!==undefined){        return hash[n];      }else{        for(var i=2;i<Math.sqrt(n);i++){          if(n%i==0){return hash[n]=false}        }        return hash[n]=true;      }    }})();
  • array de-
      method One: Var arr1=[1,2,3,2,1,2]; function Repeat1 (arr) {for (Var i=0,arr2=[];i<arr.length;i++) {if (Arr2.indexof (Arr[i]) ==-1) {Arr2.push (AR      R[i]); }}//(traversal end) return arr2;} Method Two: Hashfunction repeat2 (arr) {//iterates through each element in arr, while declaring that hash for (Var i=0,hash={};i<arr.length;i++) {//hash contains the value of the current element      Build//If not included, add a new element to the hash, with the current element value of Key,value default to 1 if (hash[arr[i]]===undefined) {hash[arr[i]]=1;    }}//(traversal end)//convert hash to index: Var i=0;    var arr2=[];    For (arr2[i++] in hash); return arr2;} Method Three: Function Repeat3 (arr) {return Arr.sort (). Join (",,"). Replace (/(^|,,) ([^,]+) (  ,, \2) */g, "$1$2"). Split (",,"); }console.log (REPEAT3 (arr1));  
  • Insert Sort
      var arr=[2,4,1,5,3]; function Insertsort (arr) {//traverse each element in arr (I starting from 1) for (Var i=1;i<arr.length;i++) {//To save the current element temporarily in the variable t var t=arr      [i]; var p=i-1;//declares the variable p=i-1//loop: (arr[p]>t&&p>=0) {while (arr[p]>t&&p>=0) {//) assigns the value of P position to        P+1 position arr[p+1]=arr[p]; p--;//p--}//(Loop end) arr[p+1]=t;//Place T in p+1 position}//(Loop End)} insertsort (arr); Console.log (String (arr));  
  • Quick sort:
      function quickSort(arr){    //如果arr的length<=1    if(arr.length<=1){      return arr;//就直接返回arr    }    //计算参照位p    var p=Math.floor(arr.length/2);    var left=[];    var right=[];    //删除p位置的元素    var center=arr.splice(p,1)[0];    //遍历arr中每个元素    for(var i=0;i<arr.length;i++){      if(arr[i]>=center){        right.push(arr[i]);      }else{        left.push(arr[i]);      }    }    return quickSort(left) .concat(center,quickSort(right))  }  var sortedArr=quickSort(arr);  console.log(String(sortedArr));
  • Regular expressions
    (1) "ryan5 is6 not7 a8 good9 man10"var n=5;var str="ryan is not a good man";str=str.replace(/\b[a-z]+\b/g,function(kw){ return kw+n++;});console.log(str);
  • the number of occurrences of each character in the statistics string is the most frequently seen?
      var str= "HelloWorld"; Method One: Use hash for (Var i=0,hash={};i<str.length;i++) {if (Hash[str[i]]) {hash[str[i]]++}else{hash[str[i]]=    1; }} console.dir (hash); method two: Use regular var arr=str.split (""). Sort (). Join (""). Match (/([A-z]) \1*/g). Sort (function (b) {retur n B.length-a.length;  }) Console.log ("Most appears:" +arr[0][0] + "Total" +arr[0].length+ "times"); var hash={};  Arr.foreach (function (val) {hash[val[0]]=val.length;  }); Console.dir (hash);  
  • Array Dimension Reduction
    var arr=[    [0,0,0,0],    [0,0,0,0],    [0,0,0,0],    [0,0,0,0],  ];  //method 1:  for(var r=0,arr1=[];r<arr.length;r++){    for(var c=0;c<arr[r].length;c++){      arr1.push(arr[r][c]);    }  }  console.dir(arr1);  //method 2:   for(var r=0,arr2=[];r<arr.length;r++){    arr2=arr2.concat(arr[r]);  }  console.dir(arr2);//method 3:  var arr2=[].concat.apply([],arr);  console.dir(arr2);
  • function Assignment
      var f=function(){var a=b=1;}  f();  console.log(b);//1  console.log(a);//报错  var f=function(){var a=b=1;}  setTimeout(f,0);  console.log(b);//报错  f();  var a,b=0, fn=function(){var a=b=2;}  fn();  console.log(a);//undefined  console.log(b);//2
  • function currying (Coliward)
      var getN;  function add(n){    getN=function(){console.log(n);}    return function(m){      n+=m;    arguments.callee.toString=function(){        return n;      }      return arguments.callee;    }  }  add(1)(2)(3); getN();//6  add(1)(2)(3)(4); getN();//10  alert(add(1)(2)(3));//6  alert(add(1)(2)(3)(4));//10
  • Recursive
    var emp={ work:function(){//3,2,1  var  sum=0;//+3+2+1 +2+1  +1  for(vari=0; i<arguments.length&&arguments[0]>0;        i++){        sum+=arguments[i]            +arguments.callee(              --arguments[i]            );      }      return sum;    }  }  console.log(emp.work(3,2,1));//10
  • Closed Package
    (1)function fun(n,o){//外层函数    console.log(o);    return {      fun:function(m){//内层函数 n        return fun(m,n);      }    }  }  var a=fun(0);a.fun(1); a.fun(2); a.fun(3);   //undefined  0      0       0var a=fun(0).fun(1).fun(2).fun(3);//undefined   0    1    2var a=fun(0).fun(1); a.fun(2); a.fun(3);//undefined  0       1      1(2)var a=0,b=0;  function A(a){    A=function(b){alert(a+b++)};    alert(a);  }  A(1);//1  A(12);//13
  • Oop
    (1) window.a=300;    function fn1 () {this.a=100;    this.b=200; return function () {alert (THIS.A)}.call (arguments[0])} function fn2 () {this.a=new fn1 ();} var a=new fn1 (). B;//300var v=new fn1 (fn2 ());//[object Object] (2) var Number=2;//4 8 var obj={number:4,//8 fn1: (Fun      Ction () {//var number; this.number*=2;number*=2;      Declare undefined var number=3 in advance;        return function () {this.number*=2;        number*=3;      alert (number);  }}) ()} var fn1=obj.fn1; alert (number); FN1 ();   Obj.fn1 (); 4 9 Alert (window.number),//8 alert (obj.number),//8 (3) function Foo () {getname=function () {alert (1);}    ; return this;} Foo.getname=function () {alert (2);}; Foo.prototype.getname=function () {alert (3);}; var getname=function () {alert (4);}; function GetName () {alert (5);}; Foo.getname ();//2getname ();//4foo (). GetName ();//1getname ();//1new foo.getname ();//2new Foo (). GetName ();//3new New Foo (). GetName ();//3 (4) var a=1;var b={A: 2, B:function () {console.log (THIS.A);//1} (), F:this.f=function () {console.log (THIS.A); }};function f () {Console.log (3);} f ();//1b.f ();//2 (B.F) ();//2 (0,B.F) ();//1 (5) var foo=function () {console.log (THIS.A);} var obj={a:2,foo:foo};var a=10;var Bar=obj.foo;var bar2=foo.bind (obj); bar ();//10bar2 ();//2foo ();//10obj.foo ();// 2setTimeout (bar,0);//10 (6) function MyObj () {this.p.pid++;} myobj.prototype.p={"pid": 0}//2myobj.prototype.getnum=function (num) {return this.p.pid+num;} var _obj1=new MyObj (); Create new object, inherit prototype Pid+1var _obj2=new MYOBJ (); Create new object, inherit prototype Pid+2console.log (_obj1.getnum (1) +_obj2.getnum (2));//7 2+1 +
  • There are five ways to determine if an object is not an array type:
    (1) typeof cannot judge only the values and functions of the original type (2) isprototypeof judge the parent and object can check the entire prototype chain//may inherit from the array Console.log (ARRAY.PROTOTYPE.ISPROTOTYPEOF ([]) ?"  is an array ":" Not an array "); Console.log (Array.prototype.isPrototypeOf ({})? "  is an array ":" Not an array "); Console.log (Array.prototype.isPrototypeOf () (function () {})? "  Array ":" is not an array ");(3) constructor check the constructor of the specified object to check the entire prototype chain//may inherit from the array var father={};  var son={};  Father.__proto__=array.prototype;  Son.__proto__=father; Console.log (Son.contructor==array? ") is the array ":" Not an array ") Console.log ({}.contructor==array?").  is an array ":" Not an array "); Console.log (function () {}.contructor==array? ")  is an array ":" is not an array ");(4) instanceof checks whether an object is an instance of a constructor that can check the entire prototype chain//may inherit from the array var father={};  var son={};  Father.__proto__=array.prototype;  Son.__proto__=father; Console.log (son instanceof Array? ")  is an array ":" Not an array "); Console.log ({} instanceof Array? "  is an array ":" Not an array "); Console.log (function () {} instanceof Array? "       is an array ":" is not an array ");(5) Forcibly use the object to be checked, calling the original ToString method without checking the entire prototype chain//[object class]: Class-array Date object//Can only check the object that was originally created by the array. Console.log (Object.prototype.toStRing.call ([]) = = "[Object Array]"? "      is an array ":" Not an array ");      Console.log (Object.prototype.toString.call ({}));      Console.log (Object.prototype.toString.call () (function () {}));      Console.log (Object.prototype.toString.call (/\d/));       var father={};       var son={};       Father.__proto__=array.prototype;      Son.__proto__=father; Console.log (Object.prototype.toString.call (son) = = "[Object Array]"? " is an array ":" is not an array ");//is not A//conclusion: Once an object is created, the class property cannot modify/modify the inheritance relationship or modify the Class Property (6) Array.isarray (obj) does not check the entire prototype chain CO      Nsole.log (Array.isarray ([]));  Console.log (Array.isarray ({})); If the browser does not support IsArray if (array.prototype.isarray===undefined) {//if (! Array.isarray)//give? Add IsArray Method Array.prototype.isarray=function (ARG) {//forcibly call the original ToString method, and "[Object Arra Y] "compare return Object.prototype.toString.call (arg) = =" [Object Array] "?"      is the array ":" is not an array "; }  }
  • Custom Object.create ()--Handwriting
      Object.create=function(father,props){      console.log("我的create");      /*使用setPrototypeOf方法      var o=Object();//1. 创建空对象      Object.setPrototypeOf(o,father);//2. 继承father      */      /*不使用setPrototypeOf方法      function Constructor(){}      Constructor.prototype=father;      var o=new Constructor();      */      Object.defineProperties(o,props);//3. 定义新属性      return o;  }
  • Principles of deep cloning
    Object.clone=function(obj){//深克隆if(typeof(obj)=="object"){//如果obj是对象  var o=//有必要区分数组和普通对象  Object.prototype.toString.call(obj)=="[object Array]"?[]:{};      for(var key in obj){//遍历obj的自有属性          //如果key是obj的自有属性          if(obj.hasOwnProperty(key)){              o[key]=arguments.callee(obj[key]);//arguments.callee调的是当前的Object.clone函数              }      }      return o;      }else{//如果obj是原始类型的值,就直接返回副本          return obj;      }  }
  • If the browser does not support the Every property, the every implementation principle
      if(Array.prototype.every===undefined){     Array.prototype.every=function(fun){      //遍历当前数组中每个元素      for(var i=0;i<this.length;i++){          if(this[i]!==undefined){//调用fun,依次传入当前元素值,位置i,当前数组作为参数  ,将返回值,保存在变量r中          var r=fun(this[i],i,this);          if(r==false){//如果r为false             return false;//返回false          }          }           }//(遍历结束)       return true;//返回true     }  }
  • If the browser does not support the some property, the some implementation principle
      if(Array.prototype.some===undefined){     Array.prototype.some=function(fun){        for(var i=0;i<this.length;i++){        if(this[i]!==unefined){          var r=fun(this[i],i,this);              if(r==true){ return true; }                }            }        return false;     }      }
  • The browser does not support the map attribute, the map implementation principle
      if(Array.prototype.map===undefined){     Array.prototype.map=function(fun){      //创建空数组: newArr      var newArr=[];      //遍历当前数组中每个元素      for(var i=0;i<this.length;i++){         //如果当前元素不是undefined         if(this[i]!==undefined){//判断稀疏数组//调用fun传入当前元素值,位置i,当前数组,将结果保存在r中              //将newArr的i位置赋值为r          var r=fun(this[i],i,this);                  newArr[i]=r;         }      }//(遍历结束)      return newArr;//返回newArr     }  }
  • If the browser does not support the reduce attribute, the implementation principle of reduce
      if(Array.prototype.reduce===undefined){     Array.prototype.reduce=function(fun,base){       base===undefined&&(base=0);       for(var i=0;i<this.length;i++){      if(this[i]!==undefined){         base=fun(base,this[i],i,this);      }           }       return base;         }  }
  • If the browser does not support the bind attribute, the implementation principle of the BIND function
         if(Function.prototype.bind===undefined){     Function.prototype.bind=function(obj/*,参数列表*/){      var fun=this;//留住this              //*****将类数组对象,转化为普通数组      var args=Array.prototype.slice.call(arguments,1);      //args保存的就是提前绑定的参数列表      /*function slice(1){         var sub=[];         for(var i=0;i<length;i++){          sub.push(arguments[i]);         }         return sub;      }*/      return function(){                 //将后传入的参数值,转为普通数组               var innerArgs=Array.prototype.slice.call(arguments);//将之前绑定的参数值和新传入的参数值,拼接为完整参数之列表         var allArgs=args.concat(innerArgs)        //调用原始函数fun,替换this为obj,传入所有参数        fun.apply(obj,allArgs);      }     }  }

Front-end JavaScript Knowledge (iii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.