1.0 variable

In JS, if a variable is not declared before assignment, assignment automatically declares it. This is not allowed in many other programming languages. We can do that, but we don’t usually do that in practice.

var mood;  // Declare variables separately
var name, age  Declare multiple variables at once

var name = "zhangzhen"  // Declare variables and assign values
var name = "zhanghen", age=30   // Declare multiple variables at once and assign values to them.
Copy the code
  • Notes:
    • Spaces and punctuation are not allowed in variable names except for the dollar sign “$”
    • You can also use a hump, capitalizing the first letter of the following word (usually used as a function name)

2.0 Data Types

2.1 String:(string)

  • The string must be enclosed in quotation marks, either single or double

  • If you want to display a single quote in the string contained by a single quote, you must escape it with a \ backslash. The same applies to double quotes

2.2 Values:(int)

  • Floating point numbers, that is, numbers with a decimal point
  • Integer, a positive integer without a decimal point
  • A negative number, a number preceded by a minus sign

2.3 Boolean value(Boolean)

  • The Boolean type has only two optional valuestrueandfalse
  • The value “true” means true, and the value “false” means false. In Chinese, “true” means yes or true, and “false” means no or false.

2.4 Array:(array)

  • Strings, numbers, and Booleans are called scalars and can only be assigned one value at a time.

  • Arrays differ greatly in that they can be used to hold a set of values, and each value in the array is an element of that array.

Against 2.4.1To declare an array:

var beatles = Array(4)   // Declare an Array with the keyword Array() and specify the initial number of elements as 4
var beatles = Array(a)// Specifying the number of elements is not required
Copy the code

2.4.2 Fill the array with elements

When you fill an array, you not only need to give the value of the new element, but you also need to give the location in the array where the new element will be stored. This location is the index of the element. Each element is assigned an index, surrounded by square brackets.

Syntax: array[index] = element;

2.4.3 Fill in the last declared array Beatles

beatles[0] = "zhenzhen"
beatles[1] = "xingfu"
Copy the code

Note: The index of an array starts at 0. 0 is the first element. For example, if there are 4 elements, the index is 0, 1, 2, 3.

Complete example:

var beatles = Array(4)
beatles[0] = "zhenzhen"
beatles[1] = "xingfu"
beatles[2] = "xiaoma"
beatles[3] = "yuxi"
Copy the code

2.4.4 Another way to declare an array

var beatles = Array("zhangzhen"."xingfu"."xiaoma"."yuxi");
Copy the code

This is a relatively simple way to declare an array, in the declaration of the array at the same time to fill it, automatically assign subscripts, each element separated by commas.

2.4.5 Declare an array in brackets

var bealtes = ["zhangzhen".1989.true."yuxi"]
Copy the code

This is a simple, straightforward way to declare an Array. There is no need to refer to the keyword Array(), and it can contain not only strings, but also values and booles.

2.4.6 The element description of an array

bealtes = Array(a);// The elements of an array can be variables
var name = "zhangzhen";
bealtes[0] = name;
     
// An element of an array can also be an element of another array
var names = ["zhengzhen".1989."Male"];
bealtes[1] = names[3];
     
// An array can contain other arrays
var lennon = ["join".1940.false];
bealtes[2] = lennon;
     
// You can even include an object. See the object section
Copy the code

2.4.7 An associative array

var lennon = Array(a)// Replacing the subscripts of array elements with strings can make the code more readable, but this is generally not recommended for arrays
lennon["name"] = "join"
lennon["year"] = 1940
lennin["living"] = false
Copy the code

3.0 object

3.1 Create an Object with the keyword Object()

// Declare an Object with the Object() keyword. Each value of the Object is a property of the Object
// Instead of using square brackets and subscripts to get the property, it uses a dot to get the property name and to get the value of the property
var lennon = Object(a); lennon.name ="zhenzhen";  // The name property of the object Lennon
lennon.year = 1940;
lennon.living = false;
Copy the code

3.2 Curly braces {} create the object

var lennon = {name:"zhengzhen".year:1940.living:false}
Copy the code

3.3 The value of a property of an object can be of any data type

// Reference the array to the object
>> var dicts = {}
>> lists = ["zhengzhen".1940.false]
>> dicts.name = lists
>> dicts.name[0] > >"zhengzhen"

// Reference the object to the array
>> var lists = Array() > >var dict = {name:"zhengzhen".year:1989.liveing:false}
>> lists[0] = dict
>> lists[0].name
"zhengzhen"

// Reference objects to objects
var dict = {}
var lennon = {name:"xingfu".year:1989.age:"Male"}
dict.person = lennon
dict.person.name
"xingfu"
Copy the code

4.0 the operator

4.1 Arithmetic operator

The arithmetic operators include: add (+), subtract (-), multiply (*), divide (/), which is consistent with the rules of addition, subtraction, multiplication and division in mathematics. If there are no parentheses, multiply and divide first, then add and subtract.

1 + 4   // Add operation
1 + (4*5)  // Multiple combination operations
(1+3) *5    // Use parentheses to separate the different operations
Copy the code

4.2 ++--+ =with- =

Year = year++ or year+=1

4.3 You can also manipulate variables

var num = 80;
var age = (num - 30) /2
Copy the code

4.4 String throughA plusCan be together

var message = "I am feeling" + "happy";
Copy the code
var mood = "happy";
var message = "I am feeling" + mood
Copy the code

It is even possible to concatenate values and strings to form a new string, which is allowed because JS is a weakly typed language.

var year = 1989;
var message = "The year is" + year
Copy the code

5.0 Conditional Statements

5.1 statement

The condition must be in parentheses after the if. The condition is always evaluated as a Boolean value, which can only be true or false.

// Standard syntax, recommended
if(1>2){
	alert("Right")}else{
	alert("Error")}// Curly braces after conditional statements are not required and can be omitted in some cases, such as when there is only one judgment
if(1>2) alert("Error")   // The alert is never executed, only if the condition is true
Copy the code

5.2 Comparison operator

Operators are almost exclusively used in conditional statements, so we’ve grouped operators in this chapter, including greater than (>), less than (<), greater than or equal to (>=), less than or equal to (<=), and equality (==). This operator consists of two equals signs. A single equals sign is an assignment and cannot be used as a comparison. The equality (==) operator does not indicate strict equality. Strict equality must be the three equal signs (== =), which is both straight and compares types; The non-equal (!=) operator consists of an exclamation mark and an equal sign.

// Example of the == operator
if(false= =' ') {False means the same as an empty string, so the result of the comparison is true
    alert('right')}// === Absolute
// Strict comparison, where both values and types are compared. One is a Boolean and the other is a string, so they are not the same type. The result of the comparison is false.
if(false= = =' '){
    alert('right')}Copy the code

5.3 Logical operator

  • “The logic is the same as (&&)”.

  • “Logic or (| |) (namely the Chinese, or mean, multiple conditions as long as meet a condition]”.

  • “Logic is not (!) Can only be used as a single logical operand, i.e. the result of that logical operation is reversed.

// Return true if both logic and, are true
if ( num > 5 && num <= 10) {
    alert("This is a number greater than 5 and less than 10.")}// Return true if one of them is true
if ( num > 10 || num <5 ) alert("This is a number greater than 10.")

// The result of the comparison is reversed
if ( !(1>2) ) alert("If 1 is less than 2, return false. This is the reverse operation, so return true and the statement will be executed!")

// You can reverse the entire conditional statement with logical nonlinearity
if ( !(num > 10 || num <5) ) alert("This is a number not greater than 10 or less than 5.")
Copy the code

6.0 Loop Statements

A loop can execute the same piece of code many times over. As long as the given condition is always met, the code contained in the loop is executed repeatedly. Once the given condition is no longer true, the loop stops.

6.1 The while loop

  • A while loop is very similar to an if statement. The syntax is almost exactly the same. The while is followed by a condition in parentheses, and the curly braces are followed by the code to execute
// While loop statement, syntax
var count = 1;
while(count < 11){
	alert(count);
	count++;
}
Copy the code

6.2 Do {} whi () loop

The main difference between the do{}while() loop and the while(){} loop is that one condition is last and one is first. This results in the do loop’s condition being executed at least once, even if it is false to begin with, because the condition is executed after the block. But the while loop doesn’t, because its condition is first.

// Loop consistent with the result of the while loop. This block of code will be executed 10 times, and the count variable will end with a value of 11
var count = 1;
do{
    alert(count);
    count++;
}while(1<11);

// If count is false and is executed at least once, then count will have a value of 2
do{
    alert(count);
    count++;
}while(count<1);
Copy the code

6.3 The for loop

The for loop is actually a variant of the while loop, or a compact version of the while loop, with the statements associated with the loop enclosed in parentheses.

// Rewrite the case of the while loop
for(var count=1; count<11; count++){
	alert(count)
}
Copy the code

The most common use of a for loop is to iterate through all the elements of an array. In this case, we often use the array array. Length property to get the number of elements in the array. It is important to note that the array elements are all started from zero, not from the beginning.

var lists = ["zhangzhen"."xingfu"."yuxi".false.1989];

// Use the for loop to iterate through an array
for(var index=0; index < lists.length; index++){
	console.log(lists[index]);
}
Copy the code

7.0 the function

If you need to use the same piece of code multiple times, you can encapsulate it as a function. Basically, a function is a set of statements that you can call anytime in your code.

7.1 Defining functions

// Define the function
function shout(){
	alert("This is the first function I declare.")}Copy the code

Now if you want to do this in your code, you can call the whole function at any time by calling the shout() statement, which is how the function is called, much less typing the same code in different places.

Case 2:

// A function that iterates over an array
function name(){
	var bealtes = ["zhangzhen"."xingfu"."yuxi".1989.false]
	for(var index=0; index<bealtes.length; index++ ){console.log(bealtes[index])
	}
}
// Call the function
name()
Copy the code

7.2 Function passing parameters

Case through the above we can see that the ability to function in the integration of the code, but found he has a little problem, is apparently only traverse function specified within that array, we not general enough, and no real embody the function of strength, we can through the following we will learn to a function parameter, to traverse different arrays, Give this function the general ability to handle this type of problem.

// Pass lists to the function, which we represent as an array
function name(lists){
	for(var index=0; index<lists.length; index++){ alert(lists[index]) } }// Suppose we have such an array
var bealtes = ["zhangzhen"."xingfu"."yuxi".1989.false]

// Use the function we just defined to iterate over the array and pass it to the function
// In a real project, of course, we would have to make a judgment on the type of the arguments passed, in case the function is capable of handling arguments that are not arrays
name(bealtes)
Copy the code

Case 3 (multiplication function) :

function ride(num1,num2){
	var multiply = num1 * num2;
	alert(multiply);
}
/ / call
ride(2.5);
Copy the code

7.3 Function assignment to variables and variable scope

For example, if we want to calculate the standard weight of an adult, the formula is: (height cm-100) ×0.9= standard weight (kg). Let’s write a function for him and return the result. In this case, we need to use the return statement.

function weight(height){
	var dvalue = height-100;
	standard = dvalue * 0.9;
	return standard;
}
// Now use this function to calculate our own standard weight.
var myheight = 175;
Another way to use a function is to use it as a data type. Assign the return value of the function to a variable and use it as the value of the variable
var mystandard = weight(myheight);
alert(mystandard)
Copy the code

Interpretation of the concept of variable scope:

In the above function we see two types of variables, one is declared inside the function, the other is declared outside the function. In the beginning we said that we must use var to declare variables, so we must also use var to declare variables inside the function. In this case, variables declared inside the function can only be called inside the function. We call them local variables. If there is a variable outside the function with the same name, then that variable will refer to the global variable outside the function.

// The concept of variable scope
function aquare(num){
	total = num * num;
	return total;
}
// The value of the global variable toatl is 50
var total = 50
// There is also a variable inside the function, which is not declared with var
var number = aquare(20)
// The value returned is 400, which changes the value of the global variable total
console.log(total)
> 400
Copy the code

Modified version:

function aquare(num){
	var total = num * num;
	return total;
}
var total = 50
var number = aquare(20)
console.log(total)
> 50
console.log(number)
> 400
Copy the code

8.0 Object details

Object is a very important data type. It is relatively abstract and complex. It will be explained in detail later.

8.1 Self-created Objects

For example, if we want to produce a car, their common properties include the color, the number of tires, the steering wheel, the seats, etc., are common properties, we can define an object for them, and put these common properties in this object. The difference is that they all have different engine sizes, and we can add another way to extend them.

function Person(){
	// The properties in this object are generic
	this.name = "zhenzhen";
	this.age = 30;
}
// Create an instance of another person whose age is different from Chang Chen's, but otherwise the same
var xinPerson = new Person();
// Add a property to the object
Person.prototype.mood = "link";

console.log(xinPerson.mood);

Copy the code

8.2 Built-in objects

Built-in objects are the default js to give us the encapsulated objects, which built-in objects and encapsulated a lot of properties, we can use directly.

8.2.1 new Array() Array object

When we use the new keyword to initialize an Array, we create an Array object.

var bealtes = new Array(a); bealtes[0] = "zhenzhen";
// Length is a built-in property of this object
bealtes.length;
Copy the code

8.2.2 new Date() Time object

Date objects are used to store and retrieve information about dates and times.

var current_date = new Date(a)// Get the week, and get a number
console.log(current_date.getDay())
// Get the hour, and get the exact time array
console.log(current_date.Hours())
Copy the code

8.2.3 New Math() object

var num = 7.561;
var num = Math.round(num);
console.log(Math)
alert(num)
Copy the code

8.2.4 Host objects

In addition to built-in objects, we can use other objects that have been predefined. These objects are not provided by the javascript language itself, but by its runtime environment. The environment is the browser, so the objects provided by the browser are called the host objects, which we’ll learn about later, the DOM and BOM.