DBI Chapter 4: Basic JavaScript

Outline

  • Explicit and implicit embedding of JavaScript.
  • Variables : types, scope
  • Numerical operators, relational operators and precedence.
  • Screen output and dialog windows.
  • Control statements.
  • Objects, and Arrays.

Java Script

There are three parts :

  • The core - includes operators, expressions, statements and subprograms;
  • Client side - includes controls of a browser and interactions with users e.g. mouse click;
  • Server side - support communication with database management system.(this module will use php)

Explicit and Implicit Embedding

  • Explicit embedding - the JavaScript code physically resides in the HTML document.
    • disadvantages:
    • Mixing the two languages in the same document.
    • The person who creates and maintains the HTML/JavaScript may not be the same person.
  • Implicit embedding - place JavaScript in its own file.
    • Advantages:
    • Hide the script from the browser user.

Enclose JavaScript Content in HTML

<!----------------------------- Example #1 -------------------------->
<!DOCTYPE html>
<html>
    <head>
        <title> My first JavaScript </title>
    </head>
    <body>
        <script type = "text/javascript">
            document.write("Hello");
        </script>       
    </body>
</html>

Including JavaScript in HTML

<script type = "text/javascript" src = "filename.js"></script>

<!----------------------------- Example #2 ------------------------->

<!DOCTYPE html>
<html>
    <head>
        <title> My first JavaScript </title>
    </head>
    <body>
        <script type = "text/javascript" src = "basic_js.js">
        </script>       
    </body>
</html>
<!-- 
Example #1 is explicit embedding whereas Example #2 is implicit embedding
-->
/*in basic_js.js*/
/*Example #1*/
document.write("Hello");

Variable Name

  • Identifier must begin with a letter, an underscore(_), or a dollar sign ($). Subsequent characters may be letters, underscores, dollar signs, or digits.
  • Case sensitive and no length limitation.
  • Cannot use reserved words:
    break, delete, function, return, typeof, case, do etc.
/*all use the same html code which is Example #2 */
/*all following code will be in the basic_js.js file*/
var result = 42;
document.write("The result is: ", result, "<br />");
/*will print The result is : 42*/

Declaring Variables

  • Values are dynamically typed.
  • There are five primitive types: Number, String, Boolean, Undefined, and Null.
  • If a variable has been explicitly declared, but not assigned a value, it has the value undefined.

Numeric Operators

  • Binary operators: +, -, *, /, %
  • Unary operators: +, -, --, ++
var result,
    pi = 3.14,
    prime = 7,
    university = "UNNC",
    nothing = null,
    isRight = true;
document.write("The values of vars are: ", result, " ", pi, " ", prime, " ", university, " ", nothing, " ", isRight, " ", "<br />");

document.write("(", prime, "++) * 3 = ",(prime++) * 3, " ", "<br />");
document.write("(++", prime, ") * 3 = ",(++prime) * 3, " ", "<br />");

1

Precedence and Associativity Rules

  • Precedence specifies which operator is evaluated first when two operators with different precedence are adjacent in an expression.
  • Associativity specifies which operator is evaluared first when two operators with the same precedence are adjacent in an expression.
  • Operator :
    ++, --, unary -, unary +
    Associativity:
    Right (though it is irrelevant)
  • Operator :
    *, /, %
    Associativity:
    Left
  • Operator:
    Binary +, Binary -
    Associativity:
    Left
  • The first operators listed have the highest precedence.
var a = 2, b = 4, c = 0, d = 0;
c = 3 + a * b;/*c = 3 + 2*4 = 11*/
d = b / a / 2;/*d = 4/2/2 = 1*/
document.write("c: ", c, " d:", d, " ", "<br />");
/*c: 11 d:1 */

Sring Catenation Operator

  • If the value of first is "Freddie", the value of the following expression is "FreddieFreeloader".
    first + "Freeloader"
    "1"+"2" = 12

Implicit Type Convention

  • convert into number
    7 * "3" =21
    (1.0 * "1") + (1.0 * "2") = 3
  • A number can be converted to a string by concatenating it with the empty string.
    7 + "" + 1 = 71
var first = "Freddie", second = "Freeloader";
var third = first + second; // FreddieFreeloader

var one = "1", two = "2";
var three = one + two;  // 12

var seven = 7, strThree = "3";
var result = seven * strThree; // number * string gets number  21
var strResult = seven + strThree; // number + string gets string 73

var decimal = 1.0;
var test = (decimal * one) + (decimal * two); //3

var empty = "";
var strResult2 = seven + empty + decimal; // number + string gets string 71

document.write(third, " ", three, " ", result, " ", strResult, " ", test, " ", strResult2, " ", "<br />");
/*
FreddieFreeloader 12 21 73 3 71 
*/

Explicit Type Conversions

var str_value = String(value);
var num = 6;
var str_value = num.toString();
var str_value_binary = num.toString(2);
var number = Number(aString)
var number = aString - 0;

var str_value = String(7);
var num = 6;

document.write((str_value + num), "<br />"); //"76"

str_value = num.toString(); //"6"
num = Number("8"); //8

document.write((str_value + num), "<br />"); //"68"

var num2 = str_value - 0;//6

document.write((num2 + num), "<br />");//14

var str_binary = num.toString(2);//1000

document.write(str_binary, "<br />");//1000
/*output
76
68
14
1000
*/

Screen Output and Dialog Windows

  • There are 3 types : alert,confirm and prompt.
  • String parameter of alert is not HTML code, but plain text.
var result = 42;
alert("The result is: " + result + "\n");

var answer = confirm("Do you want to continue?");

var name = prompt("What is your name?", "");

document.write("Answer is ", answer, ", Name is: ", name, "<br />");

alert
confirm
prompt
output

Relational Operators

  • The last two operators disallow type conversion of either operand. So "3" === 3is false whereas "3" == 3 is true.
  • Boolean operations : &&, ||, !
var three = "3";

document.write(three === 3, ", ", three == 3, "<br />");
/*false, true*/
relational operators

Selection Statements

if(a>b) {...} else {...}

Switch Statement

  • Case labels can be numbers, strings or booleans.
var bordersize;
var err = 0;
bordersize = prompt("Select a table border size: " +
        "0 (no border), " +
        "1 (1 pixel border), " +
        "4 (4 pixel border), " +
        "8 (8 pixel border), ");

switch (bordersize) 
{
    case "0": 
        document.write("<table>");
        break;
    case "1": 
        document.write("<table border = '1'>");
        break;
    case "4": 
        document.write("<table border = '4'>");
        break;
    case "8": 
        document.write("<table border = '8'>");
        break;
    default: 
        {
            document.write("Error - invalid choice: ",
            bordersize, "<br />");
            err = 1;
        }
}

if(err == 0)
{
    document.write("<tr>",
                "<td> 1 </td>",
                "<td> 2 </td>",
               "</tr>",
            "<tr>",
                "<td> 3 </td>",
                "<td> 4 </td>",
            "</tr>",
            "</table>");
}
Control
control2

Loop Statement

var text = "";
var i = 0;
do {
  text +=  "The number is " + i + " <br />";
  i++;
}
while (i < 5);
document.write(text, " <br />");

/*
The number is 0 
The number is 1 
The number is 2 
The number is 3 
The number is 4 
*/

Object Creation

  • Objects are created with a new expression.
  • In JavaScript, objects are blanks i.e. with no properties or types.
    var my_car = new Object();
    my_car.make = "Ford";
    my_car.model = "Fusion";
    Create my_car object with two properties:
    make and model
  • Alternatively
    var my_car = {make: "Ford", model: "Fusion"};

Nested Objects

  • A new object can be created as a property of another object with properties of its own.
    my_car.engine = new Object();
    my_car.engine.config = "V6";
    mycar.engine.hp = 265;

Assessing Property in Object

  • Object-dot-property notation
    var prop = my_car.make;
    var prop2 = my_car["make"];
  • For-in loop
var car = new Object();
car.make = "Ford";
car.model = "Fusion";

var cup = {colour: "Green", material: "Glass"};

document.write(car.make, ", ", car.model, " <br />");//Ford, Fusion 
document.write(cup.colour, ", ", cup.material, " <br />");//Green, Glass 

// nested object
car.engine = new Object();
car.engine.config = "V6";
car.engine.hp = "265";

// two ways of accessing property values in object
document.write(car.make, ", ", car.model, ", ", car.engine.config, ", ", car.engine.hp, " <br />");
//Ford, Fusion, V6, 265 
document.write(car["make"], ", ", car["model"], ", ", car["engine"]["config"], ", ", car["engine"]["hp"], " <br />");
//Ford, Fusion, V6, 265 

// using for-in loop
for(var i in cup)
{
    document.write("Name: ", i, "; Value: ", cup[i], "<br />");
}
//Name: colour; Value: Green
//Name: material; Value: Glass
// array 
var stack = new Array(1, 2, "three", "four");
for(var i in stack)
{
    document.write("No: ", i, "; Value: ", stack[i], "<br />");
}
/*
No: 0; Value: 1
No: 1; Value: 2
No: 2; Value: three
No: 3; Value: four
*/

// array length
document.write(stack.length, "<br />");//4

// accessing array out of bound
document.write(stack[5], "<br />"); //undefined
/*
Ford, Fusion 
Green, Glass 
Ford, Fusion, V6, 265 
Ford, Fusion, V6, 265 
Name: colour; Value: Green
Name: material; Value: Glass
No: 0; Value: 1
No: 1; Value: 2
No: 2; Value: three
No: 3; Value: four
4
undefined
*/

Conclusions

  • Core parts of JavaScript : operators, expressions, statements and subprograms.
  • Explicit and implicit embedding of JavaScript
  • Five primitive types: Number, String, Boolean, Undefined, and Null
  • Precedence adn the associativity rules
  • Object,properties and nested objects.
  • Array and how to access it.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容