Uncle Tom, the 20th lesson of the JavaScript series, the last 5 to JavaScript topics

Source: Internet
Author: User

Blog Links: http://www.cnblogs.com/TomXu/archive/2012/02/10/2342098.html

Original question:

Uncle Note: These topics are also from these 5 subjects, of course, if you can correct 4 and above and want to get high wages, please contact me.

    1. Find the largest element in a numeric array (using the Match.max function)
    2. Converts a numeric array into a function array (each function pops up the corresponding number)
    3. Sort an object array (sorting criteria is the number of attributes per element object)
    4. Use JavaScript to print out the number of Fibonacci (without using global variables)
    5. The following syntax functions are implemented: var a = (5). Plus (3). Minus (6); 2
    6. The following syntax functions are implemented: var a = Add (2) (3) (4); 9

I used to write. NET background, the operation of JS, just out of the DOM and Ajax, only for the existence of jquery can be used (not skilled)

Later on the internet found Uncle Tom's JavaScript series, found that the writing is really good. It's really me. This dom can be manipulated, Ajax can write, and jquery will work. But I hope to go further in the adoption OH.

So it took some time to learn the contents of the blog. [ This article concludes with a directory listing of JavaScript series articles]

Now start to answer, with my own ideas, (because I am not a front end, but occasionally the front-end busy, I write a DOM operation, and Ajax.jquery in the Ajax functions are not clear, but also to check the API)

So there are flaws and mistakes in the place also want to point out that learning.

First question:

Find the largest element in a numeric array (using the Match.max function).

Answer thinking: First, I have not used this function, JS comes with the parameter hint is a lump of shit, and the weak type of language, what can be passed to the inside, can be implemented on the other said.

So I baidu a bit match.max function, found inside the parameter is Math.max (1,2,3,4,5,6,7) this mode.

Removing the "content" in the left and right parentheses of the array just satisfies the requirements of the Max parameter.

So:

<script type= "Text/javascript" >        var int_array = [1,2,3,4,5,6];        var str_array = "";        for (var i = 0; i < int_array.length; i++) {          Str_array + = Int_array[i] + ",";     }           Str_array = str_array.substring (0,str_array.length-1);//This does not find a string built-in function to remove a specific tail character (trim (), trimright)//May be my parameter is not tuned    eval ("Math.max (" +str_array+ ")");    

The first one is smooth, not too difficult.

Second question: Convert a numeric array into a function array (each function pops up the corresponding number)

Thinking: Convert a number into a function array, and each function outputs a corresponding number.

The key is "eject the corresponding number."

is obviously a closure operation. (Why say "obviously", because I spent 2 days to understand and learn closures) ....

<script type= "Text/javascript" >       var int_array =  [1,2,3,4,5,6,7];        var fn_array = [];        for (var i = 0; i < int_array.length;i++) {              var f =   (function (lockitem) {                     return function () {                           Console.log ("Current is function fn_" + Lockitem + "  ----  corresponding number is:" + Lockitem);}                }) (Int_array[i]);                Fn_array.push (f);         }         for (var j = 0; J < fn_array.length;j++) {                 console.log (Fn_array[j] ());        } </script>            

  

Third question: Sort an object array (the number of attributes for each element object is the sort condition)

Answer the idea: first give an array of objects such as (var Obj_array = [{},{},{}]);

Then write a function that calculates the number of attributes per object (not including the prototype attribute) and returns the new object, which has 2 properties var newObj = {Obj:obj,count:count};//obj is the object itself that previously calculated the number of properties, Count is the number

It is then sorted based on the Count property, and the Obj property of the object is returned.

varObj_array =[{name:"Zhang San"}, {name:"Zhang San", Age:25}, {name:"Zhang San", Age:25, Address:"Wuhan, Hubei"                }            ]; functionPropertycount (obj) {if(typeofObj!== "Object"){                    Throw NewError ("parameter type is wrong!")); }                varCount = 0;  for(varPropinchobj) {                    if(Obj.hasownproperty (prop)) {count++; }                }                varObj_instance ={target:obj, count:count}returnobj_instance; }            //deletes the specified index element of an array            functionRemoveatindex (array,index) {array.splice (index,1); }            varObj_whit_propertycount = []; varSort_object = []; varI_array = [];  for(varx = 0;x < obj_array.length;x++) {Obj_whit_propertycount.push (Propertycount (obj_array[x));                I_array.push (Propertycount (Obj_array[x]). Count);            I_array.sort (); }             for(vars = i_array.length-1; S >=0;s--) {Sort_object.push (Returnobj (S+1));            } console.log (Obj_whit_propertycount);            Console.log (Sort_object); functionReturnobj (count) { for(varQ = 0;q < obj_whit_propertycount.length;q++) {                    if(Obj_whit_propertycount[q].count = =count) {                        returnObj_whit_propertycount[q].target; }                }            }

The third body is certainly not a good idea, but stumbling has been made.

Question fourth: Print out Fibonacci with JavaScript (no global variables)

I only made a recursive calculation, for printing out 1,1,2,3,5,8 .... Such numbers have not thought, if the reader, please leave a message to tell me.

function fibonacii (num) {                if(num = = 1 | | num = = 2) {                    return 1;                }                 return Fibonacii (num-1) + fibonacii (num-2);            }            Console.log (Fibonacii (// Fifth number

Question Fifth: The function of implementing the following syntax: var a = (5). Plus (3). Minus (6); 2

The answer: I first saw (5), said the truth, really meng ... How can there be such a strange grammar? Only when a function call is there will be f () Ah!!

Later think: (1+2), (9/3)-1. () is very common, is not an expression it.

Then output in the console: Console.log ((5));//The return result is the same as I expected.

As a result, we began to ponder the add and minus two functions.

Since (5) The return is a number type, I'm just going to extend these two methods directly on the prototype property of number. (not old people don't want to change the prototype object of the system)

function (NUM1) {      return this +function(NUM1) {    return   this- A;} Console.log ((5). Add (3). Minus (6));

In fact, the answer to this question, there is another way of thinking

Because number.prototype._ptoto_: Object.prototype, I can extend add and minus on the object.prototype element.

This is the code I wrote.

Object.prototype.add =function(NUM1) {////if (typeof this! = "number") {//throw new Error ("must be a numeric type");//                }//if (parseint (this) = = NaN) {//throw new Error ("must be a number");//                }                returnparseint ( This) +NUM1; } Object.prototype.minus=function(NUM1) {//if (typeof this! = "number") {//throw new Error ("must be a number!");//                }//if (parseint (this) = = NaN) {//throw new Error ("must be a number");//                }                returnparseint ( This) -NUM1; }              varresult = (5). Add (+). Minus (5); Console.log (result);

Notice where the notes are.

Question sixth: Implement the following syntax: var a = Add (2) (3) (4);

To answer the question, return the function itself after each call. But the requirements are not expected.

Because the requirements of the topic may be Add (2) (3) (4) returns only one result. I am add (2) once Add (2) (3) once Add (2) (3) (4) once.

varSum_array = []; varsum = 0; varAdd =function(a) {Sum_array.push (a); if(sum_array.length==1) {Console.log (a); return  This. Add; }Else if(Sum_array.length > 1){                     for(vary = 0;y < sum_array.length;y++) {sum+=Sum_array[y];                }} console.log (sum); return  This. Add; } Add (1) (2) (3);

Here, the 6 questions are so-so-so-so, there must be a wrong position. But I will learn and think slowly, as soon as possible to consolidate the basic knowledge of JavaScript.

PS: A colleague of the company, see I write these code, said you this is to turn the rhythm of the front desk, closures are understood.

Then I modeled a scene:

Interviewer: Closure, function on, execution context you all know, good, come to work tomorrow. By the way, you write a modal pop-up layer.

I:... No.....

Uncle Tom Blog Address: http://www.cnblogs.com/TomXu/archive/2011/12/15/2288411.html

Uncle Tom, the 20th lesson of the JavaScript series, the last 5 to JavaScript topics

Related Article

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.