Chapter One: Data structure and algorithm JavaScript description

Source: Internet
Author: User
Tags square root variable scope

In front-end engineers, there is often a voice, why we have to learn data structures and algorithms, no data structures and algorithms, we do a good job.
In fact, the algorithm is a broad concept, we write any program can be called the algorithm, even to the refrigerator to put elephants, but also through the door, put, closed the planning, we can also be regarded as an algorithm. It can be said that the simple algorithm is the human instinct. And the knowledge of the algorithm learning is to absorb the experience of predecessors. To classify complex problems, abstract, help us out of the era of slash and burn, the system master an algorithm process.

as your knowledge grows, whether it's the front end, the server, or the client, any programmer will start to face more complex problems, and the algorithms and data structures become more indispensable .

Front-end engineers should be the ones who need to focus on algorithms and data structures. Data structures and algorithms do not take care of the need to get started, so if the front-end engineers themselves do not pay attention to the basic knowledge of algorithms and data structure, it is likely to be stuck in the work of repeated labor rarely grow in such career development dilemma. The future of the Web UI, by no means by a few selector operation plus links can be dealt with. Increasingly complex products and base libraries require robust data structures and algorithms to harness.

In the past few years, thanks to platforms such as node. js and SpiderMonkey, JavaScript is increasingly used for server-side programming, where JavaScript has gone out of the browser, and programmers have found that they need more traditional languages (such as C + + and Java). The tools provided. These tools include traditional data structures (such as lists, stacks, queues, graphs, etc.) that also include traditional sorting and lookup algorithms. This series of blog posts uses JavaScript for server-side programming and how to use these data structures and algorithms.

JavaScript Programmers will find this series useful, because this book discusses how to implement data structures and algorithms under the limitations of the JavaScript language. These limitations include: arrays are objects, ubiquitous global variables, prototype-based object models, and so on . As a programming language, JavaScript has a bad reputation, and this series of blogs will showcase the good side of JavaScript to implement efficient data structures and algorithms.

The only familiar data structure is the array of programmers who have not studied computers in those schools. Arrays are undoubtedly a good choice when dealing with some problems, but for many complex problems, arrays are too primitive. Most programmers have a reason to admit the fact that for many programming problems, when they propose a suitable data structure, the algorithms designed and implemented to solve these problems become extremely easy .

The binary lookup number (BST) is one such example. Design binary difference The purpose of finding a tree is to conveniently find the minimum and maximum values in a set of data, because this data structure naturally extends a search algorithm, which is more efficient than the best query algorithm at present. Programmers who are unfamiliar with binary search trees may use a simpler data structure, but have a discount on efficiency.

learning algorithms are important because solving the same problem often allows you to use multiple algorithms. For an efficient programmer, it is important to know that the algorithm is highly efficient . For example, there are at least six or seven sorting algorithms, and if you know that fast sorting is more efficient than sorting, then it makes the sorting process efficient. Another example is that the algorithm for implementing a linear lookup is simple, but if you know that sometimes a binary lookup may be twice times faster than a linear lookup, then you are bound to write a better program.

In-depth learning of data structures and algorithms is not only known about the more efficient structures and algorithms, but also how to find the right structure and algorithms for solving the problem at hand. Writing programs, especially when it comes to JavaScript writing programs, is often weighed.

Programming environments and models for JavaScript

This chapter describes the JavaScript programming environment and BASIC programming modules, which are used in subsequent chapters to define data structures and implement various algorithms.

1.javascript has historically been a programming language that runs in browsers, but in the last few years these things have changed and JavaScript can be executed as a desktop program. Or execute on the server. Describes a programming environment: JavaScript shell, which is part of the integrated JavaScript programming environment SpiderMonkey provided by Mozilla.

2. Declaring and initializing variables

JavaScript variables are global variables by default, and strictly speaking, they do not even need to be declared before they are used. if a pre-declared JavaScript variable is initialized, the variable becomes a global variable. All, we are programmed to follow the custom of a compiled language such as C + + or Java, and declare before using variables, and the benefit is that the declared variables are local variables. The scope of variables is discussed in detail later in this chapter .

Declaring variables in JavaScript requires the use of the keyword Var, followed by the variable name, or followed by an assignment expression.

    var Number ;     var name;     var rate = 1.2;     var greeting = "Hello world!" ;     var false;

Arithmetic operators and math library functions in 3.javascript

JavaScript uses the standard arithmetic operators

+ Plus,-minus, * multiply,/divide,% excess


JavaScript also has a math library to perform advanced operations such as square root, absolute value, and trigonometric functions. Arithmetic operators follow the standard order of operations and can be used to change the order of operations using parentheses.

    var x = 3;     var y = 1.1;     + y) * y)    + y) * (x- y));          var z = 9;    Console.log (Math.sqrt (z));    Console.log (Math.Abs (Y/x))

If the accuracy of the calculation does not have to be as precise as above, you can convert the number to fixed precision

    var x = 3;     var y = 1.1;     var z = x * y;    Console.log (Z.tofixed (2));

2. Judging the structure

Judging by the value of the Boolean expression, the structure allows the program to execute the statement that the program can execute. Commonly used if and switch statements

If there are three forms of

    • A simple if statement
    • If-else statements
    • If-else-if statements

The following shows a simple if statement

    var mid =;     var height =;     var low = 1;     var current =;     var found =-1;     if (Current < mid) {        = (current-low)/2    }


The following demonstrates the If-else statement

    var mid =;     var height =;     var low = 1;     var current =;     var found =-1;     if (Current < mid) {        = (current-low)/2;     Else {        = (current + height)/2;    }

The following demo if-else-if

 var  mid = 25;     var  height = 50;     var  low = 1;     var  current = 13 var  found = -1;  if  (current < mid) {Mid  = (cur    Rent-low)/2;  else  if  (current > mid) {Mid  = (current + height)/2} else   {found  = current}  

Another decision structure is a switch statement, and the code that uses the statement is clearer when there are multiple simple choices.

3. Cyclic structure

two commonly used loop structures: the while loop and the For loop .

If you want the condition to be true, just execute a set of statements and select the While loop, which shows how the while loop works

While loop

    var number = 1;     var sum = 0;      while (Number < one) {        + = number ;         + + number    }    //

Select a For loop if you want to execute a set of statements by the number of executions. The following is an integer sum of 1 to 10 for the For Loop and

    var number = 1;     var sum = 0;      for (var number =1; number < one; number++) {        + = number ;    }    Console.log (sum)

when accessing an array, it is often used to a for loop , as follows:

    var number = [3,7,12,22,100];     var sum = 0;      for (var i = 0; i < number.length; + +i)        {+ = number[i];    }    Console.log (sum)//144

4. Functions
JavaScript provides two ways of customizing functions, one with a return value and one with no return value (this function is sometimes called a subroutine or void function).

The following shows how to customize how a function with a return value calls the function in JavaScript.

    function factorial (number) {        var product = one;          for (var i = number; I >= 1;--i) {            *= 1        }        return  product;< c16/>}    Console.log (factorial (4))

The following example shows how to define a function that does not have a return value, and uses the function not to get its return value, but to perform the operation defined in the function.

A subroutine or void function in JavaScript

    function curve (arr, amount) {        for(var i = 0; i < arr.length; + +i)            {+ =  amount;        }    }     var grades = [77,73,74,81.90];    Curve (grades,5);    Console.log (Grades)

in JavaScript, the parameters of a function are passed by value, without arguments passed by reference. But JavaScript has objects that save references, such as arrays, as in the example above, which are passed by reference .


5. Variable Scope

The scope of a variable refers to a variable in the program in which those objects can be accessed. variable scopes in JavaScript are defined as function scopes.
This refers to the value of the variable that is visible within the function that defines the variable. and a nested function defined within the function can also access the variable.

In the main program, if a variable is defined outside the function, the variable has a global scope, which means that the variable can be accessed in any part of the program that includes the body of the function. Here's a short program that shows how scopes work.

    function Showscope () {        return  scope;    }     var scope = "global";     // Global    // Global

The variable scope defined within the Showscope () function has a local scope, and the variable scope defined in the main program is a global variable. Although the two variables have the same name, they are scoped differently, and the values obtained when they are defined are different.

These behaviors are normal and expected, but if you omit the keyword var when you define a variable, everything changes . JavaScript allows you to define variables without using the keyword VAR, but the consequence is that the defined variables automatically have global scope, even if you define the variable within a function, it is also a global variable.

The following examples are the consequences of abusing global variables.

    function Showscope () {        = "local";         return scope;    }     = "global";     // Global    Console.log (Showscope ());  // Local    // Local

In the above example, the keyword VAR is omitted because the variable scope is defined within the Showscope () function. So when the string "local" is assigned to the variable, it actually changes the value of the scope variable in the main program. Therefore, when defining variables, you should always start with Var to avoid similar errors.


As we mentioned earlier, JavaScript has a function scope, meaning that JavaScript does not have block-level scopes, which is different from many other modern programming languages. With a block-level scope, you can define a variable in a piece of code that is visible only within the block and disappears from the block of code. in C + + or Java for loops, we often see examples like this

     for (int i = 1; I <=; + +i) {        << "Hello world!" << end;    }

Although JavaScript does not have block-level scopes, when we write a for loop, we assume that it has:

     for (var i = 1; I <=10; + +i) {        console.log ("hello,world!" )    }

The reason for this is that you do not want to develop bad programming habits of the helper!

6. Recursion

JavaScript allows for recursive invocation of functions, the previously defined factorial () function can also be defined using recursion

    function factorial (number) {        if (number = = 1)            {return         number  else  {            return number * factorial (number-1)        }    }    Console.log ( Factorial (///

When a function is called recursively, the result of a function's calculation is temporarily suspended when the recursion is not completed. To illustrate the process, here is a diagram showing the process of executing a function with 5 as a parameter, called the factorial () function.

5 * factorial (4)5 * 4 * factorial (3)5 * 4 * 3 * factorial (2)5 * 4 * 3 * 2 * factorial (1) 5 * 4 * 3 * 2 * 15 * 4 * 3 * 2 5 * 4 * 65 * 24120


For most cases, JavaScript has the ability to handle deeper recursive calls, but discouragement some algorithms require a recursive depth beyond the processing power of JavaScript, we need to find an iterative solution to the algorithm. Any function that can be defined recursively can be rewritten as an iterative program, which should be kept in mind.

Object and object-oriented programming

Data structures are to be implemented as objects. JavaScript provides a number of ways to create and use objects. The following shows the creation of objects and the creation and use of methods and properties in objects.

objects are created by defining a constructor that contains properties and method declarations, and immediately following the constructor with the definition of the method . Here is a constructor that checks the bank account object:

    function Checking (amount) {        this// Property this//         method This        . Withdraw = withdraw; // Method        this. tostring = tostring; // method    }

The This keyword is used to bind methods and properties to an instance of an object, and let's look at how we define the methods we've declared above.

    functionDeposit (amount) { This. Balance + =amount; }    functionWithdraw (amount) {if(Amount <= This. Balance) {             This. Balance-=amount; }        if(Amount > This. Balance) {Console.log ("Insufficient funds"); }    }    functiontoString () {return"Balance:" + This. Balance; }

Here, again, we use the This keyword and the Balance property to let the JavaScript interpreter specify that the balance property of the object that we are referencing

The complete definition and testing of the checking object is given below

    functionChecking (amount) { This. balance = Amount;//Properties         This. Deposit = Deposit;//Method         This. withdraw = withdraw;//Method         This. toString = tostring;//Method    }    functionDeposit (amount) { This. Balance + =amount; }    functionWithdraw (amount) {if(Amount <= This. Balance) {             This. Balance-=amount; }        if(Amount > This. Balance) {Console.log ("Insufficient balance"); }    }    functiontoString () {return"Balance:" + This. Balance; }    varAccount =NewChecking (500); Account.deposit (1000); Console.log (Account.tostring ());//Balance:Account.withdraw (750); Console.log (Account.tostring ());//Balance:Account.withdraw (800);//Insufficient BalanceConsole.log (Account.tostring ());//Balance:

PS: It is equally important to write code that is easy to read and to write code that allows the computer to execute correctly, as a responsible programmer must keep this in mind.

Chapter One: Data structure and algorithm JavaScript description

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.