ผลต่างระหว่างรุ่นของ "01219245/javascript1/tutorial1"

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา
แถว 86: แถว 86:
  
 
  ReferenceError: randomSolution is not defined
 
  ReferenceError: randomSolution is not defined
 +
 +
'''Notes:''' ''How to look at JavaScript console?'' In Firefox, Menu -> Web Developer -> Web Console.  In Google Chrome, Menu -> Tools -> JavaScript Console.  In Safari, TBA.  In IE, TBA.
  
 
== Functions ==
 
== Functions ==

รุ่นแก้ไขเมื่อ 02:27, 10 มกราคม 2557

This is part of 01219245

The best way to learn a language is to use it.

In this tutorial, we will write a simple number guessing game in JavaScript. Your goal is to guess a number between 1 - 100. If you guess incorrectly, a hint is given to you: if your guess is too high or too low. The game proceeds until you guess correctly.

An example of the interaction is given below:

Round 1, your guess?
40
Too low.
Round 2, your guess?
90
Too high.
Round 3, your guess?
75
Too high.
Round 4, your guess?
55
Great that's correct.

Let's get started

Before we dive in to code the game, it's best to think about the overall picture. We code in small steps, but without the overall idea, it is very easy to get lost.

What are the steps, in the program, that we have to do?

  • Random the number
  • Read the guess
  • Check the guess and give hint
  • Repeat

First sketch

If we forget all the details, our JavaScript program would look like this:

var sol = randomSolution();
do {
    var guess = readGuess();
    if ( guess == sol ) {
        congratulate();
    } else if ( guess < sol ) {
        giveHint( 'Too Low' );
    } else {
        giveHint( 'Too High' );
    }
} while ( guess != sol );

This looks like a Java program! The control statements (if and do-while) should look familiar. There are things that look like methods randomSolution, readGuess, congratulate, and giveHint. We have two variables sol and guess. If you come from Java, you should see a major difference now.

A dynamic language

In Java, you declare a variable with its type. For example, you may say int sol;. However, in JavaScript, we do not specify variable's type; we only use keyword var to declare a local variable. It is not that data in JavaScript do not have types; they do. But the type information is in each piece of the data itself, not in the variable that keeps it.

In Java, you cannot do this:

  int a = 10;
  a = "dog";      // wrong type for variable a

But it is perfectly fine in JavaScript:

  var a = 10;
  a = "dog";     // ok.  (but this is not a good practice)

(However, it is not a good practice to do so.)

Since variables in JavaScript can carry any data types, their types depend on the data that they keep. This is a dynamic behavior, i.e. it is something that you have to figure out while the program runs. This is in contrast to Java where you know the type of a variable and every data that can be refer to by the variable during the compile time.

Languages where data type information can be figured out only at run time dynamically typed languages. JavaScript, Ruby, and Python are dynamic languages. On the other hand, languages like Java, C#, and C/C++, where variable types are fully specified at their declarations, are called statically typed languages. Since you are from Java, it might be confusing. After a while, you will get used to it.

Notes: You do not need the var keyword to use variables. But these variable will become global and will be hard to reason with. Therefore, it is a good practice to always use the var keyword. We will do some experiment on this issue too.

How to run a JavaScript program?

It should be very easy to run a JavaScript program on any computers. Most web browsers can interpret JavaScript. To make our life easier, we will use jsfiddle.net.

With jsfiddle, you can type in JavaScript program in the browser and run it. You will see 4 main panels: HTML, CSS, JavaScript, and Result. Let's try our program: put our JavaScript program above in the JavaScript box, and click Run.

You'll see nothing. Why? It is because our program uses many "commands" that we haven't defined. If you look at the browser's JavaScript console, you'll see a message like:

ReferenceError: randomSolution is not defined

Notes: How to look at JavaScript console? In Firefox, Menu -> Web Developer -> Web Console. In Google Chrome, Menu -> Tools -> JavaScript Console. In Safari, TBA. In IE, TBA.

Functions

In Java, you can define methods in a class. In JavaScript, you have more freedom to define a "function" that does not belongs to any classes or objects. The code below defines function randomSolution that only returns 55.

function randomSolution() {
    return 55;
}

Let's define all other functions that our program need. At this point, we want to run our broken program.

function randomSolution() {
    return 55;
}

function readGuess() {
    return 55;
}

function congratulate() {
}

function giveHint( message ) {
}

var sol = randomSolution();
do {
    var guess = readGuess();
    if ( guess == sol ) {
        congratulate();
    } else if ( guess < sol ) {
        giveHint( 'Too Low' );
    } else {
        giveHint( 'Too High' );
    }
} while ( guess != sol );

If you paste the above program into JSFiddle and click Run, you'll see nothing, but there won't be any error message in the JavaScript console.

alert and prompt

To interact with the user, we can use "annoying" functions alert and prompt. These two functions are not part of the JavaScript language, but they are defined if you run your program in a browser.

We can modify congratulate to be

function congratulate() {
    alert( 'Great!  You guessed correctly.' );
}

If you run the program again, you should see the message.

The argument passed to alert is a String. You can use either single quotes (e.g., 'Hello') or double quotes (e.g., "Hello"). Try not to mix them in a single program.

Random numbers

Showing round numbers