JavaScript Tutorial: Variables and Operators Explained

    技术2022-05-12  34

    by Jon Perry

    As you surf the Internet, you will notice sites do things that seem impossible with HTML. They have animated pictures, they validate forms for correct input, and change content according to users' requests. They perform sums and play games. April 12, 2000

    Part 2: Object Properties and Flow Control Part 3: Functions and Classes

    These web pages are created using JavaScript, which is a language designed to work with HTML to improve and enhance a web page

    HTML can create web pages and provides a basic functional interface for the Internet. But writing it is like painting by numbers, and viewing it is like staring at cardboard.

    JavaScript provides all the features of a fully comprehensive object-orientated, event driven language, such as Java or C++, and allows direct access to the HTML document. Its advantages over these languages are that it is simple to write and simple to deploy. It doesn't need anything special to be added to a browser, and doesn't need any specialist software for its creation.

    In fact, if you have a Text Editor and a browser, you can write some JavaScript right now.

    JavaScript is contained within an HTML document. For example:

    <HTML> <HEAD> <TITLE>My First JavaScript Program</TITLE> <SCRIPT> document.write('My First JavaScript Program'); </SCRIPT> </HEAD> </HTML>

    When you save this, remember to save it with an .htm or .html extension.

    When the program is run, we see 'My First JavaScript Program' printed on the screen, without any HTML text in sight.

    The JavaScript is contained within the <SCRIPT> tags. When the browser interprets this document, it thinks 'Hmmm, this is an HTML document, titled 'My First JavaScript program', including some JavaScript - 'document.write ('My First JavaScript Program')'. Well, I better execute this. And so it does.

    Object-Orientated

    An object-orientated programming language (OOPL) is a system of keywords that perform varying actions. These keywords interact with internal data structures, known as objects, and with the computer itself.

    The name object-orientated may throw you a bit. To understand it, stop what you are doing for a while and take a look around at reality. You are quite willing to accept reality in terms of objects; there are people, cars, computers, books, chairs, shoes, pens, haircuts, birds, etc. Each of these objects can be further divided, there are tall people, short people, red cars, blue cars, PCs and Macs, and so on.

    Each of these objects does things. People talk or walk, cars go forwards or backwards, birds fly, etc.

    So, logically, when we try to model reality on a computer, we create objects.

    The characteristics of an object are called properties, for example (height, color, make), and the specific nature of each property is called a value (tall, red, PC).

    The actions of an object are called methods (talk, drive, fly).

    OOPLs also involve events. An event is something that happens, so for example, a bird could land on a branch or a haircut could change.

    Variables

    The most basic computer programming term is a variable. A variable can hold whatever we want it to.

    If we want to store our height, we would write:

    myHeight='6 foot';

    If we want to store our wealth, we would write:

    money=100;

    myHeight is known as a string, because it contains letters, and money is a obviously a number.

    We need to be able to display the contents of a variable. There are several ways of doing this, but we shall begin by using document.write, which we have already met.

    document.write(xxxx) writes the value of xxxx to the current document. xxxx may contain dynamic data, i.e. a variable.

    So,

    <HTML> <HEAD> <TITLE>JavaScript Variables</TITLE> <SCRIPT> money=100; document.write('You have '+money+' dollars to spend.'); </SCRIPT> </HEAD> </HTML>

    This program displays 'You have 100 dollars to spend.'.

    JavaScript is known as a loosely-typed language, which means we don't have to declare whether our variable is string type or integer type. This is both a blessing and a curse.

    We could write:

    myHeight='6 foot'; myHeight=7;

    This is legal in JavaScript. Equally:

    money=100; money='Fifty Quid';

    is also legal.

    We can change the value of a variable whenever we want by resetting it. Here's a program that does just that.

    <HTML> <HEAD> <TITLE>Changing Variables</TITLE> <SCRIPT> money=100; document.write('You have '+money+' dollars to spend.<BR>'); document.write('You spend 50 dollars.<BR>'); money=50; document.write('You have '+money+' dollars to spend.'); </SCRIPT> </HEAD> </HTML>

    The <BR> tags demonstrate the close link between HTML and JavaScript. We can use JavaScript to write HTML to a web page, in this case we write <BR> to force a line-break, and neatly present the story.

    We can display string variables in a similar way. This program produces exactly the same output as the previous one.

    <HTML> <HEAD> <TITLE>Changing Variables 2</TITLE> <SCRIPT> money='100 dollars'; document.write('You have '+money+' to spend.<BR>'); money='50 dollars'; document.write('You spend '+money+'.<BR>You have '+money+' to spend.'); </SCRIPT> </HEAD> </HTML>

    But this is too simple, and it is also too clumsy. To model real life, we need more flexibility with our variables. We might not always spend 50 dollars - we might not even be American!

    This introduces the next section of JavaScript, the operator.

    Operators

    An operator acts upon a variable and changes its value. This offers more control than manually setting a variable ourselves.

    Basic Operators

    Basic JavaScript operators include:

    +Addition/String addition- Subtraction*Multiplication/Division%Modulus

    Most operators are mathematical, i.e. they only work on number variables.

    Use of operators is generally very easy. If you study the financial package offered below, you can see the mathematical line is money=money-spend. The + signs scattered elsewhere in the code we'll look at in a moment.

    <HTML> <HEAD> <TITLE>Money Manager</TITLE> <SCRIPT> money=100; document.write('You have '+money+' dollars to spend.<BR>'); spend=50; money=money-spend; document.write('You spend '+spend+' dollars.<BR>You have '+money+' dollars to spend.'); </SCRIPT> </HEAD> </HTML>

    (Run the program) Try changing the values of money and spend to get different results. You will also notice how we must use numbers for the variables rather than strings if we want to use operators on them. This is typical, strings do not readily yield to subtraction, '100 dollars' - '50 dollars' is fairly meaningless to a computer because there are letters involved.

    We can perform string addition though. Here we combine two strings with a character space between them:

    <HTML> <HEAD> <TITLE>Message Maker</TITLE> <SCRIPT> greetings='Hello'; name='Jon'; document.write(greetings+' '+name); </SCRIPT> </HEAD> </HTML>

    Numbers can also be multiplied and divided. Our final operator, the percentage sign, performs modulo arithmetic, which means that the number returned is the remainder after whole number divisions are done.

    <HTML> <HEAD> <TITLE>Divide</TITLE> <SCRIPT> x=10; y=3; document.write(x/y+'<BR>'+x%y); </SCRIPT> </HEAD> </HTML>

    (Run the program) 10/3=3.333, but 10%3=1 which is the remainder after 9 (3*3) has been removed.

    If your computer displays something like 3.3333333333333335, instead of 3.3333333333333333 as you would expect, don't worry, this is the oft-mentioned floating-point bug rearing its head. Floating-point arithmetic is generally very accurate, but does get it wrong once in a while.

    Variables names often end up short and meaningless. One advantage of this is speed. Whenever a variable is used by the computer, the entire variable name needs to be passed around the system. It is quicker to pass 'x' than it is to pass 'variablerepresentingten'.

    A problem with operators occurs when we mix variable types. What are we to do with a programming instruction such as 'Jon'+1.

    JavaScript will not give an error here, instead it will return 'Jon1' as a string. 1+'Jon' becomes the string '1Jon'.

    '3'*1 gives the number 3, which is useful is we wish to treat a string as a number.

    ''+1 gives the string '1', which is useful is we wish to treat a number as a string.

    Compacted Operators

    The following operators are compactions of these basic operators.

    +=Addition/String addition with Assignment-=Subtraction with Assignment*=Multiplication with Assignment/=Division with Assignment%=Modulus with Assignment++Pre/Post Increment--Pre/Post Decrement

    An operator with an equals sign applies the right hand side to the left hand side of the expression, and stores the result in the left hand side variable.

    From the Money Manager program, we could have written:

    money-=spend; This code means exactly the same as:

    money=money-spend;

    Similarly, x=x*y; becomes x*=y; and so on.

    Pre-/Post- Operators

    The pre/post operators are a different kettle of fish.

    They do have a simple use, to add or subtract one from a number.

    e.g. if x=5; then x++ makes x=6;

    The difficulty lies in the various places these operators can be used, and in understanding the difference between pre- and post- incremention (or decrementation).

    This is best seen with an example.

    <HTML> <HEAD> <TITLE>Pre/Post Operators</TITLE> <SCRIPT> x=10; y=10; document.write('x is '+x+++', and now x is '+x); document.write('<BR>y is '+--y+', and now y is '+y); </SCRIPT> </HEAD> </HTML>

    Confusing, hey?

    Let us examine this slowly, and begin with x.

    x starts its life as 10, and is written to the document. Because we have x++, x is post-incremented, and now x is 11, which we write again.

    y also starts its life as 10. But we are pre-decrementing y. So the pre-decrement acts on the y before it is printed, so we write 9 to the document. y doesn't change after this, so we write 9 again.

    +x+++ and +--y+ are not immediately obvious statements! Put the signs before the variable and it immediately changes. Place them after and it changes afterwards.

    Comparison Operators

    The comparison operators can be used to determine relative values of variables.

    <Less than<=Less than or Equal to>Greater than>=Greater than or Equal to!=Not Equal to==Equal to

    Use of these operators involves flow controls, which control the program's flow.

    We can see one of them in action, involving the Boolean type of variable, which either returns true or false.

    <HTML> <HEAD> <TITLE>Boolean</TITLE> <SCRIPT> document.write(4>5); </SCRIPT> </HEAD> </HTML>

    4>5 is a false statement, and equates to the false variable.

    We could do this with any comparison operator to get either a true or false value.

    Logical Operators

    The logical operators perform logical operations on variables.

    &&Logical AND||Logical OR!Logical Negation?:Ternary Operator

    This is not a complete list of operators, just the essential ones.

    Part 2: Object Properties and Flow Control Part 3: Functions and Classes More articles on JavaScript
    Jon Perry is a Freelance Author and Programmer from the UK.

    最新回复(0)