当前位置:网站首页>{one week summary} take you into the ocean of JS knowledge
{one week summary} take you into the ocean of JS knowledge
2022-07-06 11:28:00 【Geek Yunxi】
Catalog
JavaScript Statement identifier
Statement ( establish ) JavaScript Variable
A sentence , Multiple variables
To declare JavaScript Variable
Objects in real life , Properties and methods
overall situation JavaScript Variable
JavaScript Lifetime of variables
To undeclared JavaScript Variable assignment value
JavaScript Math( Count ) object
JavaScript Array( Array ) object
You can have different objects in an array
example : Create a new method .
JavaScript Output
JavaScript There are no print or output functions .
JavaScript Display the data
JavaScript You can output data in different ways :
- Use window.alert() Pop up warning box .
- Use document.write() Method to write the content to HTML In the document .
- Use innerHTML Write to HTML Elements .
- Use console.log() Write to the browser's console .
Use window.alert()
You can pop up a warning box to display the data :
<!DOCTYPE html>
<html>
<body>
<h1> My first page </h1>
<p> My first paragraph .</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
operation HTML Elements
From JavaScript Visit a HTML Elements , You can use document.getElementById(id) Method .
Please use "id" Property to identify HTML Elements , and innerHTML To get or insert element content :
<!DOCTYPE html>
<html>
<body>
<h1> My first one Web page </h1>
<p id="demo"> My first paragraph </p>
<script>
document.getElementById("demo").innerHTML = " Paragraph modified .";
</script>
</body>
</html>
above JavaScript sentence ( stay <script> In the label ) Can be in web In the browser :
document.getElementById("demo") It's using id Property to find HTML Elemental JavaScript Code .
innerHTML = " Paragraph modified ." Is used to modify elements HTML Content (innerHTML) Of JavaScript Code .
In this tutorial
in the majority of cases , In this tutorial , We will use the method described above to output :
The above example directly puts id="demo" Of <p> Element write HTML Document output in progress :
writes HTML file
For testing purposes , You can use JavaScript Write directly in HTML In the document :
<!DOCTYPE html>
<html>
<body>
<h1> My first one Web page </h1>
<p> My first paragraph .</p>
<script>
document.write(Date());
</script>
</body>
</html>
Please use document.write() Just output what you write to the document . If you execute after the document has finished loading document.write, Whole HTML The page will be covered . |
!DOCTYPE html>
<html>
<body>
<h1> My first one Web page </h1>
<p> My first paragraph .</p>
<button onclick="myFunction()"> Am I </button>
<script>
function myFunction() {
document.write(Date());
}
</script>
</body>
</html>
Write to the console
If your browser supports debugging , You can use console.log() Method is displayed in the browser JavaScript value .
The browser uses F12 To enable debug mode , Click... In the debug window "Console" menu .
<!DOCTYPE html>
<html>
<body>
<h1> My first one Web page </h1>
<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>
</body>
</html>
example console Screenshot :
JavaScript sentence
JavaScript Statement to the browser . The purpose of the statement is to tell the browser what to do .
JavaScript sentence
- JavaScript Statement is a command to the browser .
- The purpose of these commands is to tell the browser what to do .
- Below JavaScript Statement to id="demo" Of HTML Element output text " Hello Dolly" :
document.getElementById("demo").innerHTML = " Hello Dolly";
A semicolon ;
Semicolons are used to separate JavaScript sentence .
Usually we add a semicolon at the end of each executable statement .
Another use of semicolons is to write multiple statements on a line .
a = 5; b = 6; c = a + b;
The above example can also be written like this :
a = 5; b = 6; c = a + b;
You may also see cases without semicolons . stay JavaScript in , Ending a statement with a semicolon is optional . |
JavaScript Code
JavaScript The code is JavaScript Sequence of statements .
The browser executes each statement in writing order .
This example outputs a title and two paragraphs to the web page :
example
document.getElementById("demo").innerHTML=" Hello Dolly"; document.getElementById("myDIV").innerHTML=" How are you doing? ?";
JavaScript Code block
JavaScript Can be combined in batches .
The code block starts with an open curly bracket , End with a closing curly bracket .
The function of a code block is to execute a sequence of statements together .
This example outputs a title and two paragraphs to the web page :
example
function myFunction() { document.getElementById("demo").innerHTML=" Hello Dolly"; document.getElementById("myDIV").innerHTML=" How are you doing? ?"; }
You will learn more about functions in later chapters .
JavaScript Statement identifier
JavaScript A statement usually takes the form of a Statement identifier For the beginning , And execute the statement .
Statement identifiers are reserved keywords and cannot be used as variable names .
The following table lists them JavaScript Statement identifier ( keyword ) :
sentence | describe |
---|---|
break | For jumping out of the loop . |
catch | Sentence block , stay try When a statement block fails to execute catch Sentence block . |
continue | Skip an iteration in the loop . |
do ... while | Execute a statement block , When the condition statement is true Continue to execute the statement block . |
for | When the condition statement is true when , The code block can be executed a specified number of times . |
for ... in | Properties used to traverse arrays or objects ( Loop through the properties of an array or object ). |
function | Define a function |
if ... else | Used to perform different actions based on different conditions . |
return | Exit function |
switch | Used to perform different actions based on different conditions . |
throw | Throw out ( Generate ) error . |
try | Implement error handling , And catch Use together . |
var | Declare a variable . |
while | When the conditional statement is true when , Execute statement block . |
Space
JavaScript Will ignore extra spaces . You can add spaces to the script , To improve its readability . The following two lines of code are equivalent :
var person="runoob";
var person = "runoob";
Break lines of code
You can use backslashes in text strings to wrap lines of code . The following example will correctly show :
document.write(" Hello \ The world !");
however , You can't fold like this :
document.write \ (" Hello world !");
Knowledge point :JavaScript It's script language , When the browser reads the code , Execute script code line by line . For traditional programming , All code will be compiled before execution .
JavaScript Variable
Variables are used to store information " Containers ".
var x=5; var y=6; var z=x+y;
It's like algebra
x=5
y=6
z=x+y
In algebra , We use letters ( such as x) To save value ( such as 5).
Through the expression above z=x+y, We can calculate z The value of is 11.
stay JavaScript in , These letters are called variables .
You can think of variables as containers for storing data . |
JavaScript Variable
Same as algebra ,JavaScript Variables can be used to store values ( such as x=5) And expressions ( such as z=x+y).
Variables can have short names ( such as x and y), You can also use better descriptive names ( such as age, sum, totalvolume).
- Variable must start with a letter
- Variables can also be $ and _ Symbol at the beginning ( But we don't recommend it )
- Variable names are case sensitive (y and Y It's a different variable )
JavaScript Statement and JavaScript Variables are case sensitive . |
JavaScript data type
- JavaScript Variables can also hold other data types , For example, text value (name="Bill Gates").
- stay JavaScript in , similar "Bill Gates" Such a text is called a string .
- JavaScript There are many types of variables , But now , We only focus on numbers and strings .
- When you assign a text value to a variable , You should enclose this value in double or single quotes .
- When the value you assign to a variable is a numeric value , Do not use Quotes . If you enclose values in quotation marks , The value is treated as text .
var pi=3.14; // If you are familiar with ES6,pi have access to const keyword , Represents a constant // const pi = 3.14; var person="John Doe"; var answer='Yes I am!';
Statement ( establish ) JavaScript Variable
stay JavaScript Creating variables in is often called " Statement " Variable .
We use var Keywords to declare variables :
var carname;
After variable declaration , The variable is empty ( It's not worth it ).
To assign a value to a variable , Please use the equal sign :
carname="Volvo";
however , You can also assign values to variables when declaring them :
var carname="Volvo";
In the following example , We've created something called carname The variable of , And assign to it "Volvo", Then put it in id="demo" Of HTML Duan Luozhong :
var carname="Volvo"; document.getElementById("demo").innerHTML=carname;
A good programming habit is , At the beginning of the code , Uniformly declare the required variables . |
A sentence , Multiple variables
You can declare many variables in one statement . This statement takes var start , And use comma to separate variables :
var lastname="Doe", age=30, job="carpenter";
Statements can also span multiple lines :
var lastname="Doe",
age=30,
job="carpenter";
Multiple variables declared in a statement cannot be assigned the same value at the same time :
var x,y,z=1;
x,y by undefined, z by 1.
Value = undefined
In a computer program , Variables with no value are often declared . Variables declared without values , The value is actually undefined.
After executing the following statement , Variable carname The value will be undefined:
var carname;
To declare JavaScript Variable
If you restate JavaScript Variable , The value of this variable will not be lost :
After the following two statements are executed , Variable carname The value of PI is still zero "Volvo":
var carname="Volvo";
var carname;
JavaScript Count
You can JavaScript Variable to calculate , It uses = and + Such operators :
y=5; x=y+2;
JavaScript data type
Value type ( Basic types ): character string (String)、 Numbers (Number)、 Boolean (Boolean)、 empty (Null)、 Undefined (Undefined)、Symbol.
Reference data type ( object type ): object (Object)、 Array (Array)、 function (Function), There are two special objects : Regular (RegExp) And the date (Date).
notes :Symbol yes ES6 A new type of raw data is introduced , Represents a unique value .
JavaScript Have dynamic types
JavaScript Have dynamic types . This means that the same variable can be used for different types :
var x; // x by undefined
var x = 5; // Now? x Is the number
var x = "John"; // Now? x For the string
The data type of the variable can use typeof Operator to see :
typeof "John" // return string
typeof 3.14 // return number
typeof false // return boolean
typeof [1,2,3,4] // return object
typeof {name:'John', age:34} // return object
JavaScript character string
Strings are stored characters ( such as "Bill Gates") The variable of .
A string can be any text in quotation marks . You can use single quotes or double quotes :
var carname="Volvo XC60";
var carname='Volvo XC60';
You can use quotation marks in strings , Just don't match the quotation marks surrounding the string :
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
You will learn more about strings in the advanced part of this tutorial .
JavaScript Numbers
JavaScript There is only one type of number . Numbers can have decimal points , It's also possible to do without :
var x1=34.00; // Use the decimal point to write
var x2=34; // Don't use the decimal point to write
The maximum or minimum number can be determined by science ( Index ) Count to write :
var y=123e5; // 12300000
var z=123e-5; // 0.00123
You will learn more about numbers in the advanced part of this tutorial .
JavaScript Boolean
Boolean ( Logic ) There are only two values :true or false.
var x=true;
var y=false;
Boolean is often used in conditional testing . You'll learn more about conditional testing later in this tutorial .
JavaScript Array
The following code creates a code named cars Array of :
var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
perhaps (condensed array):
var cars=new Array("Saab","Volvo","BMW");
perhaps (literal array):
var cars=["Saab","Volvo","BMW"];
Array subscripts are zero based , So the first project is [0], The second is [1], And so on .
You will learn more about arrays later in this tutorial .
JavaScript object
Objects are separated by curly braces . Inside the brackets , The properties of an object are in the form of name and value pairs (name : value) To define . Attributes are separated by commas :
var person={firstname:"John", lastname:"Doe", id:5566};
The object in the example above (person) There are three properties :firstname、lastname as well as id.
Spaces and breaks don't matter . Declarations can span multiple lines :
var person={
firstname : "John",
lastname : "Doe",
id : 5566
};
There are two ways to address object properties :
example
name=person.lastname;
name=person["lastname"];
You will learn more about objects later in this tutorial .
Undefined and Null
Undefined This value means that the variable has no value .
You can do this by setting the value of the variable to null To clear variables .
example
cars=null;
person=null;
Declare variable type
When you declare a new variable , You can use keywords "new" To declare its type :
var carname=new String;
var x= new Number;
var y= new Boolean;
var cars= new Array;
var person= new Object;
JavaScript Variables are objects . When you declare a variable , It creates a new object . |
JavaScript object
JavaScript Objects are data that have properties and methods .
Objects in real life , Properties and methods
In real life , A car is an object .
Object has its properties , Such as weight and color , Methods include start, stop, etc :
object | attribute | Method |
---|---|---|
car.name = Fiat car.model = 500 car.weight = 850kg car.color = white | car.start() car.drive() car.brake() car.stop() |
All cars have these properties , But the properties of each car are different .
All cars have these methods , But they are executed at different times .
JavaScript object
stay JavaScript in , Almost everything is an object .
stay JavaScript in , Objects are very important , When you understand the object , You can understand JavaScript . |
You have learned JavaScript The assignment of a variable .
The following code is a variable car Set the value to "Fiat" :
var car = "Fiat";
Object is also a variable , But objects can contain multiple values ( Multiple variables ), Each value is expressed in name:value Pair presentation .
var car = {name:"Fiat", model:500, color:"white"};
In the above example ,3 It's worth ("Fiat", 500, "white") Assign variable car.
JavaScript Objects are containers of variables . |
Object definitions
You can use characters to define and create JavaScript object :
example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Definition JavaScript Objects can span multiple lines , Spaces and line breaks are not required :
example
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
Object properties
- so to speak "JavaScript Objects are containers of variables ".
- however , We usually think that "JavaScript Objects are containers for key value pairs ".
- Key value pairs are usually written as name : value ( Keys and values are separated by colons ).
- Key value pairs are in JavaScript Objects are often called Object properties .
JavaScript Objects are containers for attribute variables . |
Object key value pairs are written similar to :
- PHP The associative array in the
- Python Dictionary in
- C Hash table in language
- Java Hash mapping in
- Ruby and Perl Hash table in
Access object properties
You can access object properties in two ways :
example 1
person.lastName;
example 2
person["lastName"];
Object methods
Object defines a function , And stored as an attribute of the object .
Object method by adding () call ( As a function ).
This instance accesses person Object's fullName() Method :
example
name = person.fullName();
If you want to visit person Object's fullName attribute , It will be returned as a string defining the function :
example
name = person.fullName;
JavaScript Objects are containers for properties and methods . |
In the following tutorial, you will learn more about functions , Knowledge of attributes and methods .
Access object methods
You can use the following syntax to create object methods :
methodName : function() {
// Code
}
You can access object methods using the following syntax :
example
objectName.methodName()
Usually fullName() As a person A method of an object , fullName As an attribute .
If you use fullName attribute , Don't add (), It will return the definition of the function :
example
objectName.methodName
There are many ways to create , Use and modify JavaScript object .
There are also many ways to create , Use and modify properties and methods .
JavaScript function
A function is an event driven or reusable block of code that executes when it is called .
example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Test case </title>
<script>
function myFunction() { alert("Hello World!"); }
</script>
</head>
<body>
<button onclick="myFunction()"> Am I </button>
</body>
</html>
JavaScript Function syntax
Functions are blocks of code wrapped in curly braces , Key words used earlier function:
function functionname()
{
// Execute code
}
When this function is called , Will execute code within the function .
Functions can be called directly when an event occurs ( For example, when the user clicks the button ), And can be JavaScript Call anywhere .
JavaScript Case sensitive . key word function Must be lowercase , And the function must be called in the same case as the function name . |
Call function with parameters
- When the function is called , You can pass values to , These values are called parameters .
- These parameters can be used in functions .
- You can send as many parameters as you want , Comma (,) Separate :
myFunction(argument1,argument2)
When you declare a function , Please declare the parameter as a variable :
function myFunction(var1,var2)
{
Code
}
Variables and parameters must appear in the same order . The first variable is the given value of the first parameter passed , And so on .
example
<p> Click this button , To call a function with parameters .</p> <button onclick="myFunction('Harry Potter','Wizard')"> Click here </button> <script> function myFunction(name,job){ alert("Welcome " + name + ", the " + job); } </script>
The above function will prompt when the button is clicked "Welcome Harry Potter, the Wizard".
Functions are flexible , You can call this function with different parameters , This will give a different message :
example
<button onclick="myFunction('Harry Potter','Wizard')"> Click here </button> <button onclick="myFunction('Bob','Builder')"> Click here </button>
According to the different buttons you click , The above example will prompt "Welcome Harry Potter, the Wizard" or "Welcome
Bob, the Builder".
Function with return value
Sometimes , We want the function to return the value to where it was called .
By using return Statement can be implemented .
In the use of return When the sentence is , Function will stop executing , And returns the specified value .
grammar
function myFunction()
{
var x=5;
return x;
}
The above function will return a value 5.
Be careful : Whole JavaScript Does not stop execution , Just a function .JavaScript Will continue to execute the code , From where the function is called .
The function call will be replaced by the return value :
var myVar=myFunction();
myVar The value of the variable is 5, That's the function "myFunction()" The value returned .
Even if you don't save it as a variable , You can also use the return value :
document.getElementById("demo").innerHTML=myFunction();
"demo" Elemental innerHTML Will become 5, That's the function "myFunction()" The value returned .
You can base the return value on the parameters passed into the function :
example
Calculate the product of two numbers , And return the result :
function myFunction(a,b) { return a*b; } document.getElementById("demo").innerHTML=myFunction(4,3);
"demo" Elemental innerHTML It will be :
12
When you just want to exit the function , You can also use return sentence . The return value is optional :
function myFunction(a,b) { if (a>b) { return; } x=a+b }
If a Greater than b, The above code will exit the function , It doesn't count a and b The sum of .
Local JavaScript Variable
stay JavaScript Variables declared within a function ( Use var) yes Local Variable , So you can only access it inside a function .( The scope of this variable is local ).
You can use local variables with the same name in different functions , Because only the function that has declared the variable can recognize the variable .
As long as the function runs , Local variables will be deleted .
overall situation JavaScript Variable
Variables declared outside functions are overall situation Variable , All scripts and functions on the web page can access it .
JavaScript Lifetime of variables
JavaScript The lifetime of variables begins at the time they are declared .
Local variables are removed after the function runs .
Global variables are deleted after the page is closed .
To undeclared JavaScript Variable assignment value
If you assign a value to an undeclared variable , This variable will be automatically treated as window A property of .
This statement :
carname="Volvo";
Will declare window A property of carname.
Global variables created by assigning values to undeclared variables in non strict mode , Is a configurable property of a global object , You can delete .
var var1 = 1; // Global properties are not configurable
var2 = 2; // Not used var Statement , Configurable global properties
console.log(this.var1); // 1
console.log(window.var1); // 1
console.log(window.var2); // 2
delete var1; // false Cannot delete
console.log(var1); //1
delete var2;
console.log(delete var2); // true
console.log(var2); // Has deleted Error reporting variable not defined
JavaScript event
HTML The incident happened in HTML Things on the element .
When in HTML Page usage JavaScript when , JavaScript These events can be triggered .
HTML event
HTML Events can be browser behavior , It can also be user behavior .
Here are HTML Instances of events :
- HTML Page load complete
- HTML input When the field changes
- HTML Button clicked
Usually , When the event occurs , You can do something .
When the event is triggered JavaScript Some code can be executed .
HTML Event attributes can be added to the element , Use JavaScript Code to add HTML Elements .
Single quotation marks :
<some-HTML-element some-event='JavaScript Code '>
Double quotes :
<some-HTML-element some-event="JavaScript Code ">
In the following example , Button element added onclick attribute ( And add the code ):
example
<button οnclick="getElementById('demo').innerHTML=Date()"> The time is now ?</button>
In the example above ,JavaScript Code will be modified id="demo" Content of element .
In the next instance , The code will modify the contents of its own elements ( Use this.innerHTML):
example
<button οnclick="this.innerHTML=Date()"> The time is now ?</button>
JavaScript Code is usually a few lines of code . It is more common to call... Through event properties : |
example
<button οnclick="displayDate()"> The time is now ?</button>
common HTML event
Here are some common HTML List of events :
event | describe |
---|---|
onchange | HTML Element change |
onclick | The user clicks HTML Elements |
onmouseover | Occurs when the mouse pointer moves over the specified element |
onmouseout | User from a HTML Occurs when you move the mouse away from the element |
onkeydown | User presses keyboard key |
onload | Browser finished loading page |
More event lists : JavaScript Reference manual - HTML DOM event .
JavaScript What can be done ?
Events can be used to process form validation , User input , User behavior and browser action :
- Event triggered on page load
- Event triggered when the page is closed
- The user clicks the button to perform the action
- Verify the validity of user input
- wait ...
There are many ways to do this JavaScript Event code :
- HTML Event properties can be executed directly JavaScript Code
- HTML Event properties can be called JavaScript function
- You can have the HTML Element specifies its own event handler
- You can stop things from happening .
- wait ...
JavaScript character string
JavaScript Strings are used to store and process text .
JavaScript character string
Strings can store a series of characters , Such as "John Doe".
A string can be any character inserted into quotation marks . You can use single quotes or double quotes :
example
var carname = "Volvo XC60";
var carname = 'Volvo XC60';
You can use the index position to access each character in the string :
example
var character = carname[7];
The index of the string is from 0 Start , This means that the first character index value is [0], The second is [1], And so on .
You can use quotation marks in strings , The quotation marks in the string should not be the same as those in the string :
example
var answer = "It's alright";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';
You can also use quotation marks by adding escape characters to the string :
example
var x = 'It\'s alright';
var y = "He is called \"Johnny\"";
String length
You can use built-in properties length To calculate the length of a string :
example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Special characters
stay JavaScript in , Strings are written in single or double quotation marks .
Because of this , The following examples JavaScript Unable to resolve :
"We are the so-called "Vikings" from the north."
character string "We are the so-called " Truncated .
How to solve the above problems ? You can use backslashes (\) To escape "Vikings" Double quotes in string , as follows :
"We are the so-called \"Vikings\" from the north."
The backslash is a Escape character . Escape character converts a special character to a string character :
Escape character (\) Can be used to escape apostrophes , Line break , quotes , And so on .
The following table lists the special characters that can be escaped with escape characters in a string :
Code | Output |
---|---|
\' | Single quotation marks |
\" | Double quotes |
\\ | The backslash |
\n | Line break |
\r | enter |
\t | tab( tabs ) |
\b | Back space |
\f | Page identifier |
Strings can be objects
Usually , JavaScript The string is the original value , You can use characters to create : var firstName = "John"
But we can also use new Keyword defines a string as an object : var firstName = new String("John")
example
var x = "John";
var y = new String("John");
typeof x // return String
typeof y // return Object
Don't create String object . It slows down execution , And may have other side effects : |
example
var x = "John";
var y = new String("John");
(x === y) // The result is false, because x Is string ,y It's the object
=== Is absolute equality , That is, the data type and value must be equal .
String properties and methods
The original value string , Such as "John", There are no properties or methods ( Because they're not objects ).
The original value can be used JavaScript Properties and methods of , because JavaScript When executing methods and properties, you can treat the original value as an object .
The string method will be introduced in the next chapter .
String properties
attribute | describe |
---|---|
constructor | Returns the function that creates the string property |
length | Returns the length of the string |
prototype | Allows you to add properties and methods to an object |
String method
For more method examples, see :JavaScript String object .
Method | describe |
---|---|
charAt() | Returns the character at the specified index position |
charCodeAt() | Returns the character at the specified index position Unicode value |
concat() | Concatenate two or more strings , Return the connected string |
fromCharCode() | take Unicode Convert to string |
indexOf() | Returns the location of the first occurrence of a specified character in a string |
lastIndexOf() | Returns the position of the last occurrence of the specified character in a string |
localeCompare() | Compare two strings in a local specific order |
match() | Find a match for one or more regular expressions |
replace() | Replace substrings that match regular expressions |
search() | Retrieve the value that matches the regular expression |
slice() | Extract a fragment of a string , And return the extracted part in the new string |
split() | Split a string into a substring array |
substr() | Extract the specified number of characters in the string from the starting index number |
substring() | Extract the character between two specified index marks in the string |
toLocaleLowerCase() | Convert the string to lowercase according to the host language environment , There are only a few languages ( Like Turkish ) With local case mapping |
toLocaleUpperCase() | Convert the string to uppercase according to the host language environment , There are only a few languages ( Like Turkish ) With local case mapping |
toLowerCase() | Convert string to lowercase |
toString() | Return string object value |
toUpperCase() | Convert strings to uppercase |
trim() | Remove white space at the beginning and end of a string |
valueOf() | Returns the original value of a string object |
JavaScript Math( Count ) object
Math( Count ) The object's function is : Perform common arithmetic tasks .
Math object
Math( Count ) The object's function is : Perform ordinary arithmetic tasks .
Math Object provides a variety of numeric types and functions . There is no need to define this object before using it .
Use Math Properties of / The grammar of the method :
example
var x=Math.PI;
var y=Math.sqrt(16);
Be careful : Math Object does not need to be defined before using this object .
Numerical value
JavaScript Provide 8 Species can be Math Object access arithmetic value :
You can refer to the following Javascript Constant usage :
example
- Math.E
- Math.PI
- Math.SQRT2
- Math.SQRT1_2
- Math.LN2
- Math.LN10
- Math.LOG2E
- Math.LOG10E
Arithmetic method
In addition to being Math Object to access the arithmetic value , There are also several functions ( Method ) have access to .
The following example uses Math Object's round Method to round a number .
document.write(Math.round(4.7));
The above code output is :
5
The following example uses Math Object's random() Method to return a value between 0 and 1 Random number between :
document.write(Math.random());
The above code output is :
0.06654728055558401
The following example uses Math Object's floor() Methods and random() To return a value between 0 and 11 Random number between :
document.write(Math.floor(Math.random()*11));
The above code output is :
1
JavaScript Array( Array ) object
The function of an array object is : Use a separate variable name to store a series of values .
Create array , For the assignment :
example
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
You can find more examples at the bottom of the page .
What is an array ?
Array objects use separate variable names to store a series of values .
If you have a set of data ( for example : Car name ), There are separate variables as follows :
var car1="Saab";
var car2="Volvo";
var car3="BMW";
However , If you want to find a car ? And not 3 car , It is 300 What about cars? ? It will not be easy !
The best way is to use arrays .
An array can store all values with a variable name , And you can access any value with a variable name .
Each element in the array has its own ID, So that it can be easily accessed .
Create an array
Create an array , There are three ways .
The following code defines a myCars Array object of :
1: The conventional way :
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2: Concise way :
var myCars=new Array("Saab","Volvo","BMW");
3: Literally :
var myCars=["Saab","Volvo","BMW"];
Access array
By specifying the array name and index number , You can access a particular element .
The following examples can be accessed myCars The first value of the array :
var name=myCars[0];
The following example modifies the array myCars The first element of :
myCars[0]="Opel";
You can have different objects in an array
be-all JavaScript Variables are objects . Array elements are objects . Functions are objects .
therefore , You can have different variable types in the array .
You can include object elements in an array 、 function 、 Array :
myArray[0]=Date.now;
myArray[1]=myFunction;
myArray[2]=myCars;
Array methods and properties
Use array objects to predefine properties and methods :
var x=myCars.length // myCars Number of elements in
var y=myCars.indexOf("Volvo") // "Volvo" The index value of the value
Create new methods
The prototype is JavaScript Global constructors . It can build new Javascript Properties and methods of objects .
example : Create a new method .
Array.prototype.myUcase=function(){
for (i=0;i<this.length;i++){
this[i]=this[i].toUpperCase();
}
}
The above example creates a new array method to convert lowercase characters of the array to uppercase characters .
This is the end of today's sharing , Friends passing by have money to hold a money market , Pay attention if you have no money , Bloggers will be closed when they see the meeting. If you read this article, you can review it. If you haven't read it, you can learn a new knowledge. Thank you .
边栏推荐
- In the era of DFI dividends, can TGP become a new benchmark for future DFI?
- Django running error: error loading mysqldb module solution
- One click extraction of tables in PDF
- 01 project demand analysis (ordering system)
- C语言读取BMP文件
- 保姆级出题教程
- Heating data in data lake?
- vs2019 桌面程序快速入门
- Software testing - interview question sharing
- wangeditor富文本引用、表格使用问题
猜你喜欢
一键提取pdf中的表格
QT creator test
Error connecting to MySQL database: 2059 - authentication plugin 'caching_ sha2_ The solution of 'password'
AcWing 1298. Solution to Cao Chong's pig raising problem
wangeditor富文本引用、表格使用问题
Vs2019 use wizard to generate an MFC Application
QT creator shape
MTCNN人脸检测
图像识别问题 — pytesseract.TesseractNotFoundError: tesseract is not installed or it‘s not in your path
Valentine's Day flirting with girls to force a small way, one can learn
随机推荐
Knowledge Q & A based on Apache Jena
yarn安装与使用
How to configure flymcu (STM32 serial port download software) is shown in super detail
Codeforces Round #771 (Div. 2)
Valentine's Day flirting with girls to force a small way, one can learn
ES6 let and const commands
[Blue Bridge Cup 2017 preliminary] grid division
Database advanced learning notes -- SQL statement
AcWing 1294. Cherry Blossom explanation
Some notes of MySQL
Face recognition_ recognition
搞笑漫画:程序员的逻辑
QT creator runs the Valgrind tool on external applications
Test objects involved in safety test
Install mongdb tutorial and redis tutorial under Windows
Deoldify项目问题——OMP:Error#15:Initializing libiomp5md.dll,but found libiomp5md.dll already initialized.
Kept VRRP script, preemptive delay, VIP unicast details
MySQL的一些随笔记录
牛客Novice月赛40
LeetCode #461 汉明距离