Page 1/2 of the JavaScript elementary tutorial (Lesson 4)

Source: Internet
Author: User

We already know that variables are numbers, strings, and object parameters. Another important part of Javascript is array.
An array is a list. Various lists, such as lists and URLs, can be stored in arrays in color lists.
Here we generate an array of colors:
Var colors = new Array ("red", "blue", "green ");
Now you have an array. What can you do with it? The advantage of an array is that each element in an array can be called by a number. The number of the first element is 0 and can be called as follows:
Var the_element = colors [0];
When executing this line of JavaScript commands, the value assigned to the the_element variable is the string "red ". You can use the element in the array by writing out the array name and placing the sequence number of the element in the array in square brackets. The sequence number of the 2nd elements in the array is 1.
Once an array is generated, you can add and modify the array values. If you want to set the 1st elements in the color array to red to purple, you can do this:
Colors [0] = "purple ";
Arrays are often used for loops. The following describes the application of arrays and loops.
Array is a very useful thing, because you can call each element in the array cyclically to execute a function. The following example shows the elements in a URL array cyclically.
First, to make this example take effect, we need to declare some variables:
Var url_names = new Array ("hits.org", "awaken.org", "bianca.com ");
Var a_url;
Next, we call each element in the array cyclically, open each URL, and treat the user to click the OK button in the alert box:
For (loop = 0; loop <url_names.length; loop ++)
{
// Make the name of a url for example http://www.hits.org/
A_url = "http: // www." + url_names [loop] + "/";
// Open a window
Var new_window = open (a_url, "new_window", "width = 300, height = 300 ");
// Wait for the click
Alert ("hit OK for the next site ");
}
First, you will notice the variable of loop from 0 to url_names.length. Put. length behind the array name because it tells you how many elements are in the array. However, note that the number of array elements is different from the index number (sequence number) of the last element of the array. If the array contains three elements, the length of the array is 3, but the index number of the last element in the array is array [2]. This is because the index number of the 1st elements in the array is array [0]. If you get an error message such as "object not found" when executing an array call, and your code contains an array, the possible cause is that you confuse the index number of the array elements with the number of elements in the array.
It may not be noticed that placing. length at the end of the array is very interesting to add some attributes to an object. This is because the array itself is an object, and length is an attribute of the array.
Another manifestation of an array term object is that you need to use a new command to generate a new array. In the preceding example, url_names = new Array (...) can be interpreted as: generate a new Array and use url_names to reference it. You can notice that when the word "new" is applied in this way, a new object is generated.
The first row in the loop generates a variable. The value is a string.
A_url = "http: // www." + url_names [loop] + "/";
When the loop starts, the initial value of the variable loop is 0. The 1st elements in the url_names array are strings "hits.org" .. so in the first loop, the variable a_url is equivalent to the string "http://www.hits.org /"..
The next line of the loop opens a window with this URL
Var new_window = open (a_url, "new_window", "width = 300, height = 300 ");
Since the names given to the window are the same each time we open the window, many windows will not be opened when we go to a new URL. If the window name "new_window" is removed from the preceding example, a new window is opened each time a loop is executed.
The first row of the loop only opens an alert box and treats the user to click the OK button.
The array can also be other elements, not just strings. Arrays can be applied to all aspects of the Document Object Model in JavaScript. The next lecture will introduce this knowledge.
The code in The onClick = "" link is as follows:
Var change = prompt ('change which image (0 or 1 )? ','');
Registry.document.images{change}.src}'three.jpg ';
In this example, we plan to use image exchange to demonstrate how arrays intervene in DOM. Let's take a look at the source code.
Document. image_name.src = 'some_image.gif ';
To do this, every image must be named. If you do not know the name of the image to be exchanged, but you know the order of the image in the HTML page. You can use its DOM number to specify the image.
The first image in an HTML file is document. images [0], the second is document. images [1], and so on. If you want to know how many images are in a file, you can check the Image array length to know: document. images. length. For example, if you want to change all images on your webpage to a Spacer GLF image, you can do this:
For (loop = 0; loop <document. images. length; loop ++)
{
Document. images [loop]. src = 'spacer.gif ';
}
Are you clear?
Okay. In the next lecture, we are going to learn functions.
Functions are the last basic component of programming. All programming languages are functions. Functions are callable and do not need to be rewritten.
If you want to teach yourself fast reading and use a long text link that tells you the current time when you click it.
For example... Time!
View Source Code:
<A href = "#" onClick ="
Var the_date = new Date ();
Var the_hour = the_date.getHours ();
Var the_minute = the_date.getMinutes ();
Var the_second = the_date.getSeconds ();
Var the_time = the_hour + ':' + the_minute + ':' + the_second;
Alert ('the time is now: '+ the_time); "> time! </A>
The details of JavaScript work here are not important; we will come back to review it later.
It is too long. If there are 10 more links at these times, you must cut and paste this program each time. This makes your HTML long and ugly. In addition, if you want to change this program, it must be changed in 10 different places.
You can write a function to execute it without having to copy the program 10 times. The functions here are easy to edit and read.
See how to write a timer function.
This HTML page contains a function called announceTime. Call annoumnceTime from a link:
<A href = "#" onClick = "announceTime ();"> time! </A>
Like this:
The downlink looks like the second lesson:
<A href = "#" onClick = "alert ('Hello! '); "> Hello! </A>
This is called calling the warning dialog box from a link. A function is like a method. The only difference is that a method is attached to an object. In this warning example, this object is a window object.
Let's return to the function itself. If you look at the source code, you will see that the function is located in the header of the HTML file.
<Html>
<Head>
<Title> NO Parameter Function </title>
<Script langauge = "JavaScript">
<! -- Hide me
Function announceTime ()
{
// Get the date, the hour, minutes, and seconds
Var the_date = new Date ();
Var the_hour = the_date.getHours ();
Var the_minute = the_date.getMinutes ();
Var the_second = the_date.getSeconds ();
// Put together the string and alert with it
Var the_time = the_hour + ":" + the_minute + ":" + the_second;
Alert ("The time is now:" + the_time );
}
// Show me -->
</Script>
</Head>
<Body>
...
</Body>
</Html>
Well, let's review this function line by line. First, all functions come from this format:
Function functionName (parameter list)
{
Statements...
}
Function naming rules are similar to variables. The first character must be a letter or a standard symbol. Other characters can be numbers or hyphens. However, you must ensure that the function does not have the same name as the defined variable. Otherwise, a bad result will appear. I use an internal capital name to name functions so that they do not happen to have the same name as the characters.
The function name is a set of parameters. This example is a function without parameters. We will introduce it in the next example.
The parameter is followed by the body of the function. This is a set of statements that you want to run after the function is called. In the following examples, I plan to use this report, so let me describe how it works.
The first line:
Var the_date = new Date ();
Get a new date object. Just as you get a new array when using an array, you need to get a date object first when you want to find out the real-time. When a new date object is found, it is automatically reset to the current date and time. To obtain this information other than the object, you must use this object method:
These methods obtain appropriate numbers from date objects.
Var the_hour = the_date.getHours ();
Var the_minute = the_date.getMinutes ();
Var the_second = the_date.getSeconds ();
You may wonder: how can I assume that the date object knows the method? Even how do I know that such a thing can be used as a date object? These reasons should be obtained from the Javascript library. I will do my best to explain the built-in Javascript objects, but it may not be clear to you completely.
The rest of the function is clear. It calls the return numbers in this way, converts them into strings, and calls the warning method to pop up a string dialog box. Note that you can call a method and function within the function. We will discuss it in detail.
Now, if you have a time Link, you may have noticed something wrong. Every time you may get such feedback: "12:12:04", this is getSecond () and the return value is "4 ". So when you merge them into time, what you see is the_minute + ":" + the_second get instead of what we want. It is easy to solve it. A new function is required to fix the merging of minutes and seconds.
See parameters and return values.
Although functions without parameters can reduce the workload of writing source code and make HTML source code readable, functions with parameters are more useful.
In the previous example, a problem occurs when the returned minute and second values are less than 10. The second value we want to see is 04, not 4. We can do this:
Var the_minute = the_date.getMinutes ();
If (the_minute <10)
{
The_minute = "0" + the_minute;
}
Var the_second = the_date.getSeconds ();
If (the_second <10)
{
The_second = "0" + the_second;
}
It will be very effective. But note that you wrote the same source code twice: if something is less than 10, add "0" in front ". Therefore, when the same code needs to be rewritten multiple times, use a function. In this example, I wrote a function named fixNumber:
Function fixNumber (the_number)
{
If (the_number <10)
{
The_number = "0" + the_number;
}
Return the_number;
}
The fixNumber parameter is the_number. A parameter is also a variable. When a function is called, its parameter value is also set. In this example, we call the function as follows:
Var fixed_variable = fixNumber (4 );
The the_number parameter is set to 4 in the function. Now you should have some knowledge about the subject of fixNumber. It means: If the variable the_number is less than 10, add a 0 before it. The new content here is the return command: returns the value of the_number. The return command is used in the following cases:
Var some_variable = someFunction ();
The value of some_variable is the return value of someFunction. In fixNumber, I add: return the_number to exit the function and return the value of the_number to any variable waiting for setup.
So I write the code like this:
Var fixed_variable = fixNumber (4 );
The initial value of the_number will be set to 4 through function calls. Then, because 4 is smaller than 10, the_number will be changed to "04 ". The value of the_number is returned, and the variable fixed_variable is set to "04 ".
To include fixNumber in the original function announceTime (), I added the following content:
Function announceTime ()
{
// Get the date, the hour, minutes, and seconds
Var the_date = new Date ();
Var the_hour = the_date.getHours ();
Var the_minute = the_date.getMinutes ();
Var fixed_minute = fixNumber (the_minute );
Var the_second = the_date.getSeconds ();
Var fixed_second = fixNumber (the_second );
// Put together the string and alert with it
Var the_time = the_hour + ":" + fixed_minute + ":" + fixed_second;
Alert ("The time is now:" + the_time );
}
It is assumed that the time link is clicked at 12:04:05. Use new Date () to get the Date, use getHours () to get the hour, and use the method to get the minute. In this example, the minute is 4, and then call fixNumber. The parameter is the_minute:
Var fixed_minute = fixNumber (the_minute );
When fixNumber () is called, the_number is set to the_minute. In this example, because the_minute is 4, the_number is set to 4.
After setting the parameters, we enter the function body. Because 4 is less than 10, the_number is changed to "04", and the the_number value is returned using the return command. After "04" is returned by fixNumber, in this example, fixed_minute is equal to "04 ".
We will study this process step by step. Assume that the time is 12:04:05.
We start with the announceTime () function.
1. the_minute = the_date.getMinutes (); then the_minute = 4
2. fixed_minute = fixNumber (the_minute); equals to the fixNumber () function and returns its value to fixed_minute
Now go to function fixNumber ()
3. The fixNumber (the_number) fixNumber () function is called with the value of the_minute. The value of the_minute is 4, so now the_number = 4
4. If (the_number <10) {the_number = "0" + the_number;} Because 4 is smaller than 10, the_number is now equal to "04"
5. Return the_number, exit the function, and return "04"
Now the fixTime () function has been exited, so now we return to announceTime ()
6. the return value of this function is "04", so fixed_minute is now equal to "04"
This example uses a function with only one parameter. In fact, you can set multiple parameters for the function. In the next section, we will talk about functions with more than one parameter.
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.