Baidu Front-end Technical College 2015JavaScript basic part code implementation

Source: Internet
Author: User

2. JavaScript data types and Language Basics (i) 2.1 Task description
    • creates a JavaScript file, such as util.js ;
    • practices methods for judging various data types, and implements the following methods in util.js
       //  Determines if arr is an array, returns a bool value  function   IsArray (arr) { //  your implement  }  //  Determine if FN is a function that returns a bool value  function   Isfunction (FN) { //  your implement } 
Problem-solving ideas:      1. Say the type of judgment, the first thought is typeof to judge, but the role of TypeOf is limited! The result of the judgment is only six: String,number,boolean,function,undfined,object; Bug,console.log (typeof null) = object, and for array, The return is full of obejct. typeof there are a lot of limitations!      2. The second method uses instanceof. such as var a = []; Console.log (a instanceof Array)//ture; Console.log (a instanceof Object)//ture; Because Array is a subclass of Object, So instanceof also has a lot of limitations!      3. Finally, an officially recognized method, and a more effective method, Object.prototype.toSting.call (arr)  == "[Object Array]" This method can judge all types! The code is as follows: 
// determines whether ARR is an array and returns a bool value function IsArray (arr) {    //  your implement    return Object.prototype.toString.call (arr) = = = "[Object Array]"//  determine if FN is a function that returns a bool value  function Isfunction (FN) {    //  your implement    return Object.prototype.toString.call (fn) = = = "[Object function]";}

    • Understand the difference between value types and reference types, understand how various objects are read, traverse, and util.js implement the following methods in:
//using recursion to implement a deep clone, you can copy a target object and return a full copy//copy of the object type is limited to numbers, strings, booleans, dates, arrays, object objects. Functions, regular objects, and so on, are not included Cloneobject (SRC) {    //your implement} //test Case: var srcobj = {A:1, B: {b1: ["Hello", "HI"], B2:"JavaScript"    }};varAbobj =srcobj;varTarobj =Cloneobject (srcobj); SRCOBJ.A= 2; srcobj.b.b1[0] = "Hello"; Console.log (ABOBJ.A); Console.log (abobj.b.b1[0]);      Console.log (TAROBJ.A); //1console.log (tarobj.b.b1[0]); "Hello"

Problem-Solving ideas: 1. First of all, the data in JS is divided into the original type and the reference type, for the original type, can be copied directly! For reference types, a pointer to the original object is referenced, so the reference type changes when the original object is changed! 2. The date in the reference type can also be referenced directly, so first determine if it is a reference type, and if not, copy it directly!     If it is a reference type, in the judgment, if it is date, then copy directly, if not an array, in the judgment, the judge is an object or array; 3. When copying, consider whether it is an inherited property or a property of its own!     PS: The function object Accomodation Suran is a reference type, but the cloning of the function is done by a shallow clone! The code is as follows:
//using recursion to implement a deep clone, you can copy a target object and return a full copy//the type of object being copied is limited to numbers, strings, booleans, dates, arrays, object objects. Does not include functions, regular objects, etc.functionCloneobject (src) {//your implement    varResult//define the results after cloning    if(typeof(src) = = = "Object") {//determine if a reference type        if(Object.prototype.toString.call (src) = = = "[Object Data]") {//If the data type, direct cloningresult =src; }        Else{resule= (Object.prototype.toString.call (src) = = = = "[Object Array]")? []:{};//determine the type of the object first            if(Src.hasownproperty (i)) {//determines whether the property of the object itself                if(typeofSrc[i] = = "Object") {//If you are an object, traverse replicationResult[i] =Cloneobject (Src[i]); }                Else{//if an array, one-to-one cloning! Result[i] =Src[i]; }            }        }    }    Else{//when the original type, copy directly! result =src; }}

    • Learn about arrays, strings, numbers, and other related methods, and util.js implement the following functions in
//The array is de-iterated, only considering that the elements in the array are numbers or strings, returning a de-Uniqarray (arr) {    //your implement}//Use example var a = [1, 3, 5, 7, 5, 3];varb =Uniqarray (a); Console.log (b);//[1, 3, 5, 7] //remove the opening and closing blanksfunctionTrim (arr) {//your implement}//use example var str = ' hi! ';str =trim (str); Console.log (str);//' hi! '//implements a method that iterates through an array, executes the FN function for each element in the array, and passes the array index and elements as parameters to function each (arr, fn) {    //your implement}//where the FN function can accept two parameters: item and Index//Use the example var arr = [' Java ', ' C ', ' php ', ' html '];functionoutput (item) {Console.log (item)}each (arr, output); //Java, C, PHP, HTML//Use the example var arr = [' Java ', ' C ', ' php ', ' html '];functionoutput (item, index) {console.log (index+ ': ' +Item)}  Each (arr, output); //0:java, 1:c, 2:php, 3:html//gets the number of first-level elements inside an object, returning an integer function getobjectlength (obj) {}//use example var obj = {A:1, B:2, C: {c1:3, C2:4}};console.log (getobjectlength (obj)); //3

Problem-Solving ideas: 1. Go to the heavy, directly iterate through the array, using the array's IndexOf method, to determine whether the new array exists in the array of each position of the value, if not present, add into the array, anyway discarded.     2. Remove the opening and closing blanks, take advantage of the regular expression, then replace the match to the beginning and end of the white space character!     3. For each element is executed once, see Code! 4. First define a count, which holds the number of keys to appear, because the keys are in the first layer of the object! The code is as follows:
//The array is de-iterated, only considering that the elements in the array are numbers or strings, returning a de-re-functionUniqarray (arr) {//your implement    varresult = [];//defines a new array to hold elements that are not duplicated     for(vari = 0; i < arr.length; i++) {        if(Result.indexof (arr[i]) = 1) {Result.push (arr[i]); }    }    returnresult;} //Many students certainly do not see the above code, next, we really achieve a trim//Remove a space character from the tail of a string, including full-width half-width spaces, tab, and so on, returning a string//try to complete the topic using a simple one-line regular expressionfunctionTrim (str) {//your implement    varresult = ""; Result= Str.replace (/^\s+|\s+$/g, ""); returnresult;} //implements a method that iterates through an array, executes the FN function for each element in the array, and passes the array index and elements as parametersfunctionEach (arr, fn) {//your implement    if(!IsArray (arr)) {        return false; }    if(!isfunction (FN)) {        return false; }     for(vari = 0; i < arr.length; i++) {fn (arr[i],i); }}  //gets the number of first-level elements inside an object, returning an integerfunctiongetobjectlength (obj) {varCount = 0;  for(varKeysinchobj) {Count++; }    returncount;}

    • To learn the regular expression, util.js complete the following code
// determine if the e-mail address is function Isemail (emailstr) {    //  your implement}//  Determine whether it is a mobile phone number  function  ismobilephone (phone) {    //  your implement}

Resources: Regular Expressions 30-minute introductory tutorialThe http://deerchao.net/tutorials/regex/regex.htm code is as follows:
// determine if it is an e-mail address function Isemail (str) {     var reg =/^ ([a-za-z0-9_-]) [email protected] ([a-za-z0-9_-]) + ((\.[ a-za-z0-9_-]{2,3}) {$/});      return reg.test (str);} // determine if the phone number is function Ismobilephone (phone) {    //  your implement      var reg =/^1[3-8]\d{ 9}/      return  reg.text (phone);}

Baidu Front-end Technical College 2015JavaScript basic part code implementation

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.