Home >Web Front-end >JS Tutorial >JavaScript Beginner Tutorial (Lesson 4)_Basic Knowledge

JavaScript Beginner Tutorial (Lesson 4)_Basic Knowledge

PHP中文网
PHP中文网Original
2016-05-16 19:15:251168browse

We have learned that variables can be numbers, strings and object parameters. There is another important part of Javascript: arrays.
An array is a list. Various lists such as lists, URLs, and color lists can be stored in arrays.
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 arrays is that the individual elements in the array can be called numerically. The number of the first element is 0 and can be called in the following way:
var the_element = colors[0];
When this line of JavaScript instructions is executed, the value assigned to the variable the_element is the string "red". You can call an element in an array by writing its name and placing its sequence number in square brackets. The sequence number of the second element in the array is 1.
Once the array is generated, you can add and modify the array values. If you plan to change the first element of the color array from red to purple, you can do this:
colors[0] = "purple";
Arrays are often used in loops. The application of arrays and loops will be discussed below.
Arrays are a very useful thing because you can loop through each element in the array to perform a certain function. The following is an example of looping through the elements in a URL array.
First, to make this example work, we need to declare some variables:
var url_names = new Array("hits.org","awaken.org","bianca.com");
var a_url;
Next, we loop through each element in the array, open each URL and wait for the user to click the OK button of the alert box:
for(loop=0; loop {
// make the name of a url, for example http://www.php.cn/
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 that the loop goes from 0 to the url_names.length variable. Putting .length after the array name tells you how many elements there 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 there are 3 elements in the array, 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 first element in the array is array[0]. If you get an error message such as "object not found" when performing an array call, and your code has an array, it is possible that you are confusing the index number of the array element with the number of elements in the array.
You may also notice that placing .length at the end of the array is a bit like attaching some properties to an object. This is because the array itself is an object, and length is an attribute of the array.
Another manifestation of the array term object is that you need to use new instructions to generate new arrays. In the above example, url_names = new Array(...) can actually be interpreted as: generate a new array and use url_names to make a reference to it. You can notice that when the word "new" is used in this way, a new object is created.
Line 1 in the loop generates a variable. Its assigned 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 first element of the url_names array is the string "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 the URL
var new_window=open(a_url,"new_window","width=300,height=300");
Since we give the window the same name every time we open it, many windows will not open when going to a new URL. If we remove the window name "new_window" in the above example, a new window will be opened each time through the loop.
Line 3 of the loop just opens an alert box and waits for the user to click the OK button.
Arrays can also contain other elements, not just strings. Arrays can be applied to various aspects of the JavaScript Document Object Model. This knowledge will be covered in the next lecture.
The following is the code in the onClick="" link:
var change=prompt('Change which image (0 or 1)?','');
window.document.images[change]. src='three.jpg';
This example intends to use image exchange to demonstrate how arrays intervene in the DOM. Try this example and look at the source code.
document.image_name.src = 'some_image.gif';
In order to do this, each image needs to be named. If you don't know the names of the pictures you want to exchange, but you know their order in the HTML page. The image can be specified by its DOM number.
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 there are in a document, you can check the image array length: document.images.length. For example, if you want to change all the graphics in your web page to a Spacer GLF image, you can do this:
for(loop=0; loop {
document. images[loop].src = 'spacer.gif';
}
Is it clear?
Okay. In the next lesson we are going to learn about functions.
Function is the last basic component that needs to be learned in programming. All programming languages ​​are functions. Functions are things that are callable every time and don't need to be rewritten.
If you want to teach yourself to read quickly and use a long text link that once clicked tells you the current time.
For example... time!
Look at the source code:
Time!
The details of how JavaScript works here are not important; we will come back to review it later.
The important thing is that it is too long. If there are 10 more of these time links, you will have to cut and paste this program each time. This makes your HTML both long and ugly. Also, if you want to change this program, you have to change it in 10 different places.
You can write a function to execute instead of copying the program 10 times. The function usage here makes it easy to edit and read.
Please see how to write a timing function.
This HTML page contains a function called announceTime. Calling annoumnceTime from a link:
Time!
Like this:
The downward line looks like Lesson 2:
Hello!
This is called calling the alert dialog from a link. A function is like a method, the only difference is that the method is attached to an object. In this warning example, the object is a window object.
Let’s go back 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.
                                                                                                             
            
            
        
        
        ...
        
    
    好,让我们逐行复习这个函数。首先,所有函数来自于该种格式:
    function functionName(parameter list)
    {
        statements ...
    }
    函数的命名规则于变量差不多。第一个字符必须是字母或一标准符号。其余字符可为数字或一横线。但必须保证函数不于已定义的变量同名。否则将出现很糟糕的结果。我是用内部大写的方式命名函数以保证它们不与字符碰巧重名。
    函数名后是一组参数。本例是无参数的函数,下一例中我们再举例描述。
    参数后是函数的主体。这是一组当函数调用后是想运行的语句。在下面几个例子中,我打算利用这个报时器,所以让我描述一下它是怎样工作的。
    第一行:
    var the_date = new Date();
    取得一个新的日期对象。就象你在用数组时取得一个新的数组一样,在你要找出即时是什么时间时你需要先取得一个日期对象。当找到了一个新的日期对象,它自动重置到当前的日期和时间。为了在对象以外得到这个信息,你必须使用这种对象方法:
    这些方法从日期对象上取得了合适的数字。
    var the_hour = the_date.getHours();
    var the_minute = the_date.getMinutes();
    var the_second = the_date.getSeconds();
    你可能疑惑:我怎样能假定日期对象知道何种方式?甚或我如何知道有这样一件事可作为日期对象?这些缘由应从Javascript库中获取,我将尽我所能解释内置Javascript对象,但不一定能彻底的使你清楚。
The rest of the function is clear. It calls this method to return numbers, turns them into strings, and calls the alert method to pop up a string dialog box. Note that you can call a method and function inside a function. We will discuss this in detail.
Now if you have played through Time Link, you may have noticed something wrong. You may get this feedback every time: "12:12:04", which is the return value of getSecond() as "4". Then when you combine it into a time, what you see is the_minute ":" the_second gets 14:4 instead of what we want. Solving it is an easy task, requiring a new function to patch the combined minutes and seconds value.
Please see the parameters and return values.
Although parameterless functions are very useful in reducing the workload of writing source code and making HTML source code more readable, functions with parameters are more useful.
In the previous example, problems will occur when the returned minutes and seconds are less than 10. The seconds 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 of it. So consider using functions when rewriting the same code multiple times. In this example, I wrote a function called fixNumber:
function fixNumber(the_number)
{
if (the_number < 10)
{
the_number = "0" the_number; 🎜 >                                                                                          A parameter is also a variable whose value is set when the function is called. In this example, we call the function like this:
var fixed_variable = fixNumber(4);
The_number parameter is set to 4 in the function. By now you should have some understanding of the body of fixNumber. What it means is: if the variable the_number is less than 10, add a 0 in front of it. The new content here is the return instruction: return the value of the_number. The return instruction will be used in the following situations:
var some_variable = someFunction();
The value of the variable some_variable is the return value of the function someFunction(). In fixNumber, I added: return the_number, then exit the function and return the value of the_number to any variable waiting to be set.
So, I write the code like this:
var fixed_variable = fixNumber(4);
The initial value of the_number will be set to 4 through the function call, and then since 4 is less than 10, the_number will be changed to " 04". Then the_number value is returned and fixed_variable will be set to "04".
To include the fixNumber in the original function announceTime(), I added the following:
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);
} Assumed time When the link was clicked, the time was 12:04:05. Use new Date() to get the date, use getHours() to get the hour, use the previous method to get the minute, the minute should be 4 in this example, and then call fixNumber with the parameter the_minute:
var fixed_minute = fixNumber(the_minute) ;
When fixNumber() is called, the parameter the_number is set to the_minute. In this example since the_minute is 4, the_number will be set to 4.
After setting the parameters, we enter the function body. Since 4 is less than 10, the_number is changed to "04", and then the_number value is returned with the return instruction. When "04" is returned by fixNumber, fixed_minute in this example is equal to "04".
Let’s study the process step by step. Assume the time is 12:04:05.
We start from the function announceTime()
1.the_minute = the_date.getMinutes(); then the_minute = 4
2.fixed_minute = fixNumber(the_minute); is equal to the function fixNumber() and returns its value to fixed_minute
Now enter the function fixNumber()
3. The function fixNumber(the_number)fixNumber() is called with the value of the_minute, the_minute value is 4, so now the_number = 4
4. If (the_number < 10 ) {the_number = "0" the_number;} Since 4 is less than 10, the_number is now equal to "04"
5. Return the_number value, exit the function and return the value "04"
Now the function fixTime() has been exited , so now we return to announceTime()
6. The function returns a value of "04", so fixed_minute is now equal to "04"
This example uses a function with only one parameter. You can actually set multiple parameters for a function. In the next lecture we will talk about functions with more than one parameter.

This is an array I defined:
var monkeys = new Array("mattmarg","wendy","kristin","tim","aaron", "luke");
var kittyphile = new Array("wendy","ruby","roscoe","tim");
var discophile = new Array("mattmarg", "john travolta", "wendy");
var happy = new Array("tim", "wendy","stimpy", "aaron");
var cranky = new Array("ren", "mattmarg","luke");
With The definitions of these arrays are given by the arrayIntersect function. We can easily find out that those net monkeys love disco: Dancing Net Monkeys
Notice that although John Travolta loves disco, he is not in the monkeys list, so he is not just a monkey. To call the function value, Dancing Monkey can do this:
dancing monkeys
This is a function with 3 parameters: a name representing the intersection, the first array, and the second array. It's also easy to spot the names of cat-loving cybermonkeys.
Take a look at the source code:
cat-loving monkeys
Let Let’s look at the arrayIntersect function itself:
function arrayIntersect(intersect_name, array_1, array_2)
{
var the_list = "";
for (loop_1=0; loop_1        {
for (loop_2=0; loop_2                                                                                                    The_list = the_list array_1[loop_1] " " ;
                                                                   See if you understand the loop in this example. The key is the first line of the function:
function arrayIntersect(intersect_name, array_1, array_2)
A function called arrayIntersect is defined here, which has 3 parameters. Just like in the above example, each parameter is like a variable and is assigned a value when the function is called. Therefore, when the function is called:
arrayIntersect('dancing monkeys',monkeys,discophile);
The following assignment:
intersect_name = 'dancing monkeys'
array_1 = monkeys
array_2 = disco phile
The only thing to note is that you must call the function with the correct number of parameters. If you call arrayIntersect like this:
arrayIntersect(monkeys,discophile);
it will go wrong. Try it and see what errors occur.
In any standard Javascript program, functions are basic components. Therefore it is extremely important to understand how it works. This concludes the fourth lesson.
There are two main parts to JavaScript: the language itself and its objects. In the syntax introduced in Lesson 2, we have looked at variables, statements, and if
statements, which are the building blocks of all programming languages. Now let’s learn the rest of Java script syntax.
For JavaScript syntax, we only have three questions left to learn: loops, arrays and functions.
Let’s start with the loop.
Sometimes you want to do the same thing over and over again. You want to ask someone for a password, and you keep asking until you get the correct password. If you just want to give them two tries
you can do this:
var the_password = "pass the wrench";
var answer = prompt("What's the woyd?","" );
If (Answer! = The_password) {
Answer = Prompt ("What's the woyd?", "");
if (password! = The_password) {
document.write ("" "" " You lost!

");
                                    document.write ("That's right!

");
}
Unfortunately this doesn't work if you keep asking until you get the right answer. If you wanted to ask four times instead of two, that would already be
very annoying. You'll be using four levels of if statements, which is never a good thing.
The best way to do similar things over and over again is to use a loop. In this case, you can use a loop to keep asking for the password until the person
says it. Here is an example of a while loop working with the password: pass the wrench.
var password="pass the wrench";
var answer;
while (answer != password)
{
answer = prompt("What's the woyd?","");
}
In this typical Javascript, we start with a double variable declaration:
var password="pass the wrench";
var answer;
Here we define the password as a string and we declare a variable called answer. You'll understand why we have to declare an answer immediately. The following lines are very important:
while (answer != password)
{
answer = prompt("What's the woyd?","");
}
This is a while loop. The general format of a while loop is:
while (some test is true)
{
do the stuff inside the curly braces
}
The above lines indicate: "When answer is not equal to Password , execute the prompt command. "This loop will continue to execute the statements within the curly brackets until the condition is not met. In the case where the word entered by the user is consistent with the password (i.e. Pass the wrench), the condition is not met.
Since an error will occur on some browsers when executing a test such as (answer!=password) on an undeclared variable, we must declare answer. Since the answer will be assigned a value through the prompt scheme in the while loop, answer will have no value the first time we perform the loop. Define it in advance and set its initial value to "".
Because undefined loops are often used, loops are often used to execute a set of statements a specific number of times. Another loop will be used in the next tutorial to demonstrate how to do this.
We have seen a lot of requested
var width = prompt("How many x's would you like? (1-10 is good)","5");
Next, declare some variables:
var a_line=""; Var Loop = 0;
Now, the key:
While (loop & lt; width)
{
a_Line = A_LINE "x"; > }
That is to say: "When the variable loop is smaller than the requested X`S line width, add another X to the line and then add 1 to the loop value." The loop will continue to add an X to the line and Add 1 to the loop value
until the loop is no longer smaller than the requested line width. Please see the following source code analysis:
First time
a_line = "" (because the initial value is "")
loop=0 (because the initial value is 0)
width=2 (assigned by the user Value)
0 is smaller than 2, so
a_line = a_line "x", so a_line = "x"
loop=loop 1, so loop = 1
Return to loop:
Second times
loop=1
width=2
a_line = "x"
1 is smaller than 2, so
a_line = a_line "x", so now a_line = "xx"
loop=loop 1, so now loop = 2
Return to loop:
The third time
loop=2
width=2
a_line = "xx"
2 is not less than 2, So exit the loop and continue executing:
followed by:
alert(a_line);
Start a warning dialog box.
This kind of loop is so common that programmers have developed some simple methods. The conditional loop can be written like this:
while (loop < width)
{
a_line = "x"; // Quite In a_line = a_line "x";
loop ; // Equivalent to loop=loop 1;
}
The first line, "x", means "itself plus x". If there is already a_number=5, then it can be written as, a_number =3, that is to say: a_number=a_number 3. Programmers are just so lazy.
Downward, loop, means "add 1 to itself". So loop is: loop=loop=1. It can also be written as loop =1. This lazy behavior is very effective.
Just like there is more than one way to add 1 to a number, there is more than one way to write a loop. While loops are not the only loop pattern, another popular loop is the for loop.
The while loop in the above example can be written in the following form:
var a_line="";
var loop = 0;
while (loop < width)
{
a_line = " x";
loop ;
}
It can also be written as a For loop:
var a_line="";
for (loop=0; loop < width; loop )
{
a_line = "x";
}
The format of the for loop is:
for (initial value; test; increment)
{
do this stuff;
}
In this way, the above for loop sets loop=0 and continues to add 1 until loop One thing should be understood before we use loops: loops can be nested. Here is an example of nested loops.
This is the program:
var height = prompt("How high do you want the grid? (1-10 is good)","10");
var width= prompt("How wide do you want the grid? (1-10 is good)","10");
var a_line;
var new_window = window.open("/webmonkey/98/04/files1a/grid.html", "looper","width=400,height=400");
new_window.document.writeln("

A Grid

");
for (height_loop=0; height_loop< height ; height_loop )
{
a_line = "";
for(height_loop=0; height_loop a_line = "" ;
       }
new_window.document.writeln(a_line "
");
}
After requesting the height and width, open a new window, write a header for it, and enter the for loop. The first for loop sets a_line="". Try this example without this line and see what happens. After initializing a_line, the program enters the next for loop. When the width reaches the required value, X`S lines are created and displayed in a new window. These will happen height times.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn