1, Write location
you don't need any special software to write JavaScript scripts. An ordinary text editor and a Web browser are enough for programming. Code written in JavaScript must be executed through an HTML/XHTML document. There are currently two ways to call JavaScript. The first method is to put the JavaScript code between the < script > tags in the < head > tag of the document. The code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script> alert("first javascript script") </script> </head> <body> </body> </html>
another way is to save the JavaScript code as a separate file with the extension js. The typical approach is to place a < script > tag in the < head > part of the document and point its src attribute to the file. The code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="index.js"></script> </head> <body> </body> </html>
but the best way is to put the < script > tag at the end of the HTML document. Before < body > ends the tag, the code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div>All content</div> <script> alert("first javascript script") </script> </body> </html>
the < script > tag in the previous code does not contain the traditional type = "text/javascript" attribute, because in the HTML5 specification, the script attribute is text/javascript by default, so it can be omitted, but in the HTML4.01 and XHTML1.0 specifications, the type attribute is required.
2, Basic grammar
the rules of language structure are grammar. Like written human language, each program also has its own grammar. The syntax of JavaScript is very similar to Java and C + + languages.
1. Grammatical structure
① JavaScript programs are written in Unicode character set. It is a case sensitive language, that is, when entering keywords, variables, function names and all identifiers, they must adopt consistent letter case format. However, HTML is not case sensitive (XHTML is case sensitive), which is easily confused because it is closely related to JavaScript.
② JavaScript ignores spaces, tabs and line breaks between marks in the program. Spaces, tabs and line breaks can be used arbitrarily in the program, so developers can layout JavaScript code in a neat and consistent way to increase the readability of the code.
③ simple statements in JavaScript are usually followed by semicolons (;), just like statements in C, C + + and Java. This is mainly to separate statements. However, if the statements are placed in different lines, the semicolon can be omitted. The specific code is as follows:
var a = 1 var b = 3 var c = 6;var d = 9
note: VAR here is equivalent to our java int, and all types in JavaScript are var. In idea development, a warning will be given when VaR is used because the ES6 specification proposes two ways to declare variables, let const. Let is mainly used to solve the problem of promoting the scope of VaR variables, while const is mainly used to solve the problem of constants. The following code cannot access c variables in java, but it can in JavaScript. It is easy to cause errors in development, so let is added to solve this problem. When VaR is replaced by let, an error c is not defined will be reported. In fact, for developers who have studied java, using let is more like java syntax.
<script> if (true) { var c = 10; } console.info(c);//10 </script>
however, omitting semicolons is not a good development habit in development work. We should be used to programming with semicolons.
④ Like Java, JavaScript also supports C + + and C-type annotations. JavaScript ignores any text between "/ /" and the end of a line as a comment. In addition, the text between "/ (asterisk)" and "* / (asterisk)" will also be treated as a comment. This comment can span multiple lines, but there can be no nested comments.
⑤ JavaScript identifiers are the same as java syntax.
3, Data type
JavaScript is a weakly typed language, which means that Web front-end developers can change the data type of variables at any stage without having to declare the data type of variables at the same time as strong typed languages. For example, the following statements are illegal in strongly typed statements, but can be successfully parsed in JavaScript.
var age = "three"; age = 3;
Next, we will briefly introduce the three basic data types allowed in JavaScript.
① String (string)
a string consists of zero or more characters. Characters include (but are not limited to) letters, numbers, punctuation marks and spaces. The string must be enclosed in quotation marks, either single quotation marks or double quotation marks. JavaScript can choose quotes at will, but it's best to choose according to the characters contained in the string. That is, if the string contains double quotation marks, the whole string is contained in single quotation marks; If you include single quotation marks, put the whole character in double quotation marks. The following code is shown:
var mood = "don't ask"; var mod = 'China"Flying man"Win the gold medal';
if there are both single quotation marks and double quotation marks in a string, in this case, the single quotation marks or double quotation marks need to be regarded as an ordinary character rather than the end flag of the string. In this case, the character needs to be escaped, and the string needs to be escaped with a backslash in JavaScript.
in the development work, in order to develop a good programming habit, it is recommended that whether double quotation marks or single quotation marks are used to wrap strings, they should be consistent in the whole script to ensure the regularity of use. If double quotation marks and single quotation marks are used irregularly in the same script, the code will become difficult to read.
② number
if you want to assign a value to a variable, you don't have to limit that it must be an integer. JavaScript allows the use of numeric values with decimal points and any decimal places. Such numbers are called floating point numbers. The main data types of numeric values are as follows:
var num = 33.5; num = 88; num = -6.78;
③ boolean
another important data type of JavaScript is Boolean. Boolean data has only two optional values: true or false. In a sense, programming for a computer is dealing with Boolean values. As the most basic fact, all electronic circuits can only recognize and use Boolean data; There is current in the circuit or there is no current in the circuit. The Boolean value is not a string. Never enclose the Boolean value in quotation marks. The Boolean value false and the string value "false" are two completely unrelated things.
4, Operators and process control
1. Arithmetic operator + - * /% + + - different from java, the division result is decimal. Other uses are the same as java.
2. The assignment operator = + = - = * = / =% = is the same as java, which will not be repeated here.
practice:
1. Beggars: a beggar went to the overpass to ask for money
- I asked for 1 yuan on the first day
- I asked for 2 yuan the next day
- I asked for four dollars on the third day
- Eight dollars on the fourth day
- And so on: what is the income of beggars working for 10 days?
Reference code:
<script> var sum = 0; var temp = 1; for (var i = 0; i < 10; i++) { sum += temp; temp *= 2; } alert(sum) </script>
Process control statement
If switch while do while for ternary operator is the same as java.
if is different from java. In many cases, it does not need to use = = null judgment. if will automatically determine and filter the values as undefined, null, empty string and number 0.
<script> let id;//Undefined if (id) { alert("not") } let id = undefined;//Undefined if (id) { alert("not") } id = null; if (id) { alert("not") } id = ""; if (id) { alert("not") } id = " "; if (id) { alert("yes") } </script>
At the same time, a for in is added in JavaScript. For in is generally used to traverse arrays. The usage is as follows:
<script> let arr = ["aa", "bb", "cc"]; for (let i = 0; i < arr.length; i++) { console.info(arr[i]); } for (let i in arr) { console.info(arr[i]) } </script>
In addition, the break, continue and try catch finally statements and usage are the same as those of java, and will not be repeated here.
try { console.log(b); console.log("I won't output it. Don't look for it") } catch (error) { console.log("An error has occurred") }
Exercise: complete the following exercise using JavaScript syntax
1. Factorial sum: write a JavaScript program to output 1 on the console+ 2!+ 3!+……+ 10! And. Note: 8= 8765432*1
2. Chicken and rabbit in the same cage: there are 35 heads on the top and 90 feet on the bottom. How many are each?
Reference code:
<script> let sum = 0; let out = 1; for (let i = 1; i <= 10; i++) { sum += out; out = 1; for (let j = i; j >= 1; j--) { out *= j; } } console.info("And are:", sum) for (let i = 0; i <= 35; i++) { //Assuming I is the number of chickens, the number of rabbits is 35-i if ((i * 2 + (35 - i) * 4) == 90) { console.info("Chicken:", i); console.info("Rabbit:", (35 - i)); } } </script>
5, Method (function)
if you need to use the same piece of code multiple times, you can package them into a function. A function is a set of statements that can be called at any time in your code. Each function is actually a short script.
as a good programming habit, you should define functions before calling them. A simple function definition code is as follows
function fun() { console.info(123) }
This function will output 123 on the console. Now, if you want to execute this action in your own script, you can execute this function at any time with the following statement.
fun();
The input of the function is the same as that of java, except that the type of the variable and the return type are omitted.
function fun(i1, i2) { return i1 + i2; }
In ES6, in order to simplify the code, the arrow function is introduced. For example, the above method can be simplified as follows. When calling, it is still called in the same way as fun(12,14).
var fun = (i1,i2)=>{return i1+i2}
note: when the method does not define shape parameters, you can obtain the parameters of the method through arguments, which is an indexed json object. Get the corresponding parameters through [index].
<script> function fun() { console.info(arguments[0])//12 console.info(arguments[1])//45 } fun(12, 45) </script>
6, Scope of variable
variables can be global or local. The difference between global variables and local variables lies in their scope. Global variables can be referenced anywhere in the script, and their scope is the whole web page. A local variable exists only inside the function that declares it. It cannot be referenced outside the function. The scope is only a specific function. Therefore, you can use both global and local variables in functions.
variables can be explicitly declared through the var keyword. If var is used in a function, the variable will be regarded as a local variable, which only exists in the context of the function; On the contrary, if var is not used, this variable is regarded as a global variable. If a global variable with the same name already exists in the script, this function will change the value of the global variable. An example is as follows:
function f1(i, y) { aa = 12; return i + y; } var rs = f1(12, 15); alert(aa)
7, Object
object is a very important data type. Object is a self-contained data set. The data contained in object can be accessed in two forms: attribute and method: attribute is a variable belonging to a specific object; method is a function that can be called only by a specific object.
an object is a data entity composed of some attributes and methods. In JavaScript, attributes and methods are accessed using "point" syntax. Its specific usage is as follows:
let user = { name: "Zhang San", age: 18, say: function () { alert("I am:" + this.name) } } console.info(user.name) console.info(user.say())
in ES6, corresponding abbreviations are provided for the properties and methods of objects. The following code is exactly the same as the above, but it's best not to use the arrow function (this will cause problems).
let name = "Zhang San"; let age = 18; let user = { name, age, say() { alert("I am:" + this.name) } } console.info(user.name) console.info(user.say())
The syntax of class is proposed in ES6, which is similar to java syntax. The class name is named with an initial capital hump (not mandatory).
class Person { constructor(name, age) { this.name = name; this.age = age; console.info(name, age); } showPerson(){ console.info(this.name,this.age) } } let person = new Person("Zhang San", 12); console.info(person.name); console.info(person.age); person.showPerson();
1. Built in objects
some objects are built in JavaScript, such as the Array used earlier. When we use the new keyword to initialize an Array, we are actually creating a new instance of the Array object. The specific code is as follows:
var beatles = new Array();
Array object is just one of many JavaScript built-in objects. Others include math objects and Date objects, which provide many useful methods for people to process numeric values and Date values respectively. For example, the round method of Math object can round decimal values to the nearest integer. The specific code is as follows:
var num = 13.546; var out = Math.round(num); alert(out);
The Date object can be used to store and retrieve information related to a specific date and time. When creating a new instance of date object, the JavaScript interpreter will automatically initialize it with the current date and time. The specific code is as follows:
var cd = new Date(); console.info(cd)
The Date object provides a series of methods such as getDay(), getHours(), and getMonth(), which are used to retrieve various information related to a specific date.
2. Host object
in addition to built-in objects, you can also use some other pre-defined objects in JavaScript scripts. These objects are not provided by the JavaScript language itself, but by its running environment. In Web applications, this environment is the browser, and the predefined objects provided by the browser are called host objects.
host objects include Form, Image and Element, which can be used to obtain information about forms, images and various Form elements on the web page. The most important host object is the document object, which will be introduced in subsequent chapters.
8, Common interaction events
Common interaction events for common elements are as follows:
1.onclick mouse click
2. Onmousenter mouse entry
3. Onmousesave mouse away
Case:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <button onclick="_click()">I have a surprise</button> <div onmouseenter="_mouseenter()" onmouseleave="_mouseleave()">Come in and try</div> <script> function _click() { alert("pleasantly surprised!") } function _mouseenter() { console.info("Just try") } function _mouseleave() { console.info("Come again next time") } </script> </body> </html>
Common interaction events for form elements are as follows:
1.onfocus get focus
2.onblur loses focus
3.oninput text content changes
<input type="text" onfocus="_focus()" onblur="_blur()" oninput="_input()"> <script> function _focus() { console.info("Activated") } function _blur() { console.info("Lose focus") } function _input() { console.info("Text content changes") } </script>
Common interaction events are not limited to the above. Go to W3C to find some useful methods to record them.
Chapter exercise:
Create three buttons on the page with the contents of "question 1", "question 2"..., and call the following methods when clicking.
1. Method 1: print all integers between 1 and 1000 that can be divided by 3, 5 and 7 at the same time on the console.
2. Method 2: create an array to store the names of all students, click the "question 2" button, and one student will pop up randomly each time. After all students are popped up, a prompt will pop up. No students can pop up.
3. Method 3: Click to pop up the current system time in the format of yyyy MM dd HH:mm:ss
Reference code:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Chapter exercise</title> <script> function t1() { for (var i = 0; i < 1000; i++) { if (i % 3 == 0 && i % 5 == 0 && i % 7 == 0) { console.info(i) } } } var arr = ["Zhang San", "Li Si", "WangTwo ", "Pockmarks"]; function t2() { if (arr.length == 0) { alert("No students can pop up") return; } var i = Math.floor(Math.random() * arr.length); alert(arr[i]); arr.splice(i, 1); } function t3() { var date = new Date(); alert(date.getFullYear() + "year" + (date.getMonth() + 1) + "month" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds()) } </script> </head> <body> <button onclick="t1()">Question 1</button> <button onclick="t2()">Question 2</button> <button onclick="t3()">Question 3</button> </body> </html>