Document is a javascript built-in object that represents the document part of the browser
document.write("Hello Javascript"); writes a string to the document
<html> <body> </body> <script> document.write("Hello Javascript"); </script> </html>
This is a simple example of the combination of javascript and DOM
οnclick="… "Indicates what to do after clicking the button
document.getElementById get the specified element according to id
. style.display = 'none' hidden
. style.display = 'block' display (to be exact, in block form)
<html> <body> <button onclick="document.getElementById('test').style.display='none'">disappear</button> <button onclick="document.getElementById('test').style.display='block'">visible</button> <p id='test'>test text</p> </body> <script> </script> </html>
javascript code must be placed in a script tag
The script tag can be placed anywhere in html. It is generally recommended to put it in the head tag. Once loaded, it will be executed
<html> <head> <script> document.write("is test demo") </script> </head> </html>
If there are multiple sections of script code, they will be executed from top to bottom
<html> <head> <script> document.write("First paragraph javascript"); </script> <script> document.write("The second paragraph javascript"); </script> </head> </html>
As with css, when there are too many javascript codes and they are written in html, it will be more complicated and difficult to maintain.
At this time, you can use the same means as css to separate the javascript code, put it in a file separately, and reference the file in html.
Prepare a hello.js. The content is document.write("hello javascript"); note, do not write
script tags
Two under the same level path
//js document.write("is test outside js");
<html> <script src="./helloWorld.js"></script> </html>
console.log
Several basic types
Declare unassigned and output undefined
var x;
document.write("is test " + x);
Use typeof to judge data type
var x; document.write('When declared but not assigned, the type is: '+typeof x); document.write("<br>"); x=5; document.write('When 5 is assigned, the type is: '+typeof x); document.write("<br>"); x=5.1; document.write('Assignment is 5.1 After that, the types are: '+typeof x); document.write("<br>"); x=true; document.write('Assignment is true After that, the types are: '+typeof x); document.write("<br>"); x="hello"; document.write('Assignment is hello After that, the types are: '+typeof x);
When declared but not assigned, the type is: undefined
When 5 is assigned, the type is: number
When 5.1 is assigned, the type is: number
When the value is true, the type is: boolean
After being assigned to hello, the type is: string
javascript is a very interesting language. Even basic types are pseudo objects, so they all have properties and methods.
The type of variable a is a string, and its length is obtained by calling the attribute length of the pseudo object
No matter Number,Boolean or String, there is a toString method for conversion to String
When Number is converted to string, there are two modes: default mode and base mode
var a=10; document.write('In default mode, the number 10 is converted to decimal'+a.toString()); //Default mode, decimal document.write("<br>"); document.write('In base mode, the number 10 is converted to binary'+a.toString(2)); //Base mode, binary document.write("<br>"); document.write('In base mode, the number 10 is converted to octal'+a.toString(8)); //Base mode, octal document.write("<br>"); document.write('In base mode, the number 10 is converted to hexadecimal'+a.toString(16)); //Base mode, hex document.write("<br>");
In default mode, the number 10 is converted to the decimal 10
In base mode, the number 10 is converted to the binary 1010
In base mode, the number 10 is converted to the octal 12
In base mode, the number 10 is converted to hexadecimal a
javascript provides the built-in functions parseInt() and parseFloat(), respectively, which are converted to numbers
document.write("String\"10\"Converted to digital:"+parseInt("10")); //Transform integer document.write("<br>"); document.write("String\"3.14\"Converted to digital:"+parseFloat("3.14"));//Convert floating point document.write("<br>"); document.write("String\"10abc\"Converted to digital:"+parseInt("10abc")); //Judge each bit until you find the one that is not a number document.write("<br>"); document.write("String\"10abc8\"Converted to digital:"+parseInt("10abc8") +"<br>"); //Judge each bit until you find the one that is not a number document.write("String\"hello javascript\"Converted to digital:"+parseInt("hello javascript")); //NaN - Not a Number, if not at all document.write("<br>"); //String"10"Converted to digital:10 //String"3.14"Converted to digital:3.14 //String"10abc"Converted to digital:10 //String"hello javascript"Converted to digital:NaN
Use the built-in function Boolean() to convert to a Boolean value
When converting a string:
true if not empty
When converting numbers:
true if not 0
When converting objects:
Non null is true
document.write("empty string '' converted to Boolean value:" + Boolean(""); / / empty string document.write("<br>"); document.write("non empty character 'hello javascript' string converted to Boolean value:" + Boolean("hello javascript")); / / non empty string document.write("<br>"); document.write("number 0 converted to Boolean value:" + Boolean (0)); / / 0 document.write("<br>"); document.write("number 3.14 converted to Boolean value:" + Boolean(3.14)); / / not 0 document.write("<br>"); document.write("value after null conversion of empty object to Boolean:" + Boolean (null)); / / null document.write("<br>"); document.write("non empty object new Object() converted to Boolean value:" + Boolean(new Object())); / / the object exists document.write("<br>"); Empty string '' converted to Boolean: false Value after conversion of non empty character 'hello javascript' string to Boolean: true Value after the number 0 is converted to a Boolean: false Value after the number 3.14 is converted to Boolean: true Value after null conversion of null object to Boolean: false Value after non empty object new Object() is converted to Boolean: true
The difference between Number() and parseInt()
Like parseInt(), Number() can be used to convert numbers
The difference is that when the converted content contains non numbers, Number() will return NaN(Not a Number)
parseInt() depends on the situation. If it starts with a number, it will return the legal part of the beginning. If it starts with a non number, it will return NaN
document.write("the number after converting the string '123' through the Number() function:" + Number("123")); / / normal document.write("<br>"); document.write("the Number obtained by converting the string'123abc'through the Number() function:" +Number("123abc")); / / contains a non number document.write("<br>"); document.write("the number after converting the string 'abc123' through the Number() function:" + Number("abc123")); / / contains non numbers document.write("<br>"); document.write("the number after converting string '123' through parseInt() function:" + parseInt("123")); / / normal document.write("<br>"); document.write("the number obtained by converting the string '123abc' through the parseInt() function:" + parseInt("123abc")); / / contains non numbers and returns the legal part at the beginning document.write("<br>"); document.write("the number after converting the string 'abc123' through the parseInt() function:" + parseInt("abc123")); / / contains non numbers, starts with non numbers, and returns NaN document.write("<br>"); The number obtained by converting the string '123' with the Number() function: 123 The number obtained by converting the string '123abc' with the Number() function: NaN The number obtained by converting the string 'abc123' with the Number() function: NaN The number after converting the string '123' through the parseInt() function: 123 The number after converting the string '123abc' through the parseInt() function: 123 The number after converting the string 'abc123' through the parseInt() function: NaN
The difference between String() and toString()
String() and toString() return strings, the difference is the handling of null
String() returns the string 'null'
toString() will report an error, and the following code cannot be executed
String(null) converts an empty object to a string: null null.toString() will report an error, so the following code cannot be executed
function
Function keyword is used to define a function
print is the name of the function
() indicates a list of parameters, such as no parameters
{indicates the start of the function
}End of function
The definition of function is not enough. It will not be executed automatically and needs to be called
<script> function print(){ document.write("this sentence is printed by a custom function"); } print(); </script> This sentence is printed by a custom function
Function with return value
function print(message){ document.write(message); } function calc(x,y){ return x+y; } var sum = calc(500,20); print(sum); 520
Calculator, taking value and assigning value with document
<html> <head> <meta charset='UTF-8'/> <script src="./helloWorld.js"></script> </head> <body> <div> <input type='text' id='num1'/><span>+</span><input type='text' id='num2'/><span>=</span><input type='text' id='num3'/><button onclick='caculate()'>Calculation</button> </div> </body> </html> function caculate(){ var num1 = document.getElementById('num1').value; var num2 = document.getElementById('num2').value; num4 = document.getElementById('num3').value = parseInt(num1) + parseInt(num2); }
Mouse click event
<script> function showHello(){ alert("Hello JavaScript"); } </script> <button onclick="showHello()">Click on it.</button>
Absolutely equal, absolutely not equal
Different from the judgment of whether the values are equal, absolute equal = the judgment of the type will also be performed
For example, when comparing the number 1 with the string '1', the value is equal, but the type is different
So it will return true, but = it will return false
Absolutely not equal to! = = is the same as above
ternary operator
Three operators?: there are three operands
If the first returns true, the second operator is returned
Otherwise, the third operator is returned.
var movie = age<18?"Cartoon":"You'll see";
Use?: three-phase operation method for judgment.
Age < 18? "Cartoon": "you understand"
It means when the age is less than 18, watch cartoon, or you will understand
The value of the age variable is 15, so the card is returned
Get the numerical day of the week from the date object
var day=new Date().getDay();
JavaScript provides an error handling mechanism for try catch. When an error is thrown, you can catch it
function f1(){ //Function f1 exists } try{ document.write("Attempt to call a function that does not exist f2()<br>"); f2(); //Call function f2() that does not exist; } catch(err){ document.write("Error generation caught:"); document.write(err.message); } document.write("<p>Because the error is caught, subsequent code can continue to execute</p>");
Indicates not a number
function p(s){ document.write(s); document.write("<br>"); } var a = new Number("123abc"); / / create a Number object with a non Number to get a NaN p('the value of Number object a created by the non numeric string "123abc" is' + a'); p('however, a==Number.NaN will return: '+ (a==Number.NaN)); / / even a NaN is not equal to Number.NaN p('the correct way to determine whether it is a NaN is to call the isNaN function: '+ isNaN(a)); / / the correct way is to use the isNaN() function to determine whether it is a NaN The value of Number object a created by the non numeric string "123abc" is: NaN However, a==Number.NaN will return: false The correct way to determine whether it is a NaN is to call the isNaN function: true//true: it is not a number, false: it is a number
Returns the decimal representation of a number
var a = new Number("123"); p("Digital object 123 passes toFixed(2) Keep two decimal places:"+a.toFixed(2)); //Keep two decimal places var b = new Number("3.1415926"); p("PI adopt toFixed(3) Keep three decimal places:"+b.toFixed(3));//Keep three decimal places
A scientific notation for returning a number
var a = new Number("123"); p("number object 123 is expressed by toExponential return counter" + a.toExponential()); var b = new Number("3.1415926"); p("number object 3.1415926 is expressed by toExponential return counter" + b.toExponential()); Number object 123 expresses 1.23e+2 by toExponential return counting method Number object 3.1415926 expressed by toExponential return counting method 3.1415926e+0
localeCompare compares whether two strings are the same. 0 means the same, and non-0 means different
var x = new String("Hello"); var y = new String("Hello"); var z = new String("aloha"); document.write( 'Character string x Value: '+x); document.write('<br>'); document.write( 'Character string y Value: '+y); document.write('<br>'); document.write( 'Character string z Value: '+z); document.write('<br>'); document.write('adopt localeCompare()judge x and y Are they equal? '+x.localeCompare(y)); document.write('<br>'); document.write('adopt localeCompare()judge x and z Are they equal? '+x.localeCompare(z)); document.write('<br>'); document.write('0 Representation equality<br>'); document.write('1 Indicates alphabetical order<br>'); document.write('-1 Indicates alphabetical order<br>'); //Value of string x: Hello //Value of string y: Hello //Value of string z: aloha //adopt localeCompare()judge x and y Are they equal? 0 //adopt localeCompare()judge x and z Are they equal? 1 0 Representation equality 1 Indicates alphabetical order -1 Indicates alphabetical order
Convert string to array based on separator
split converts a string to an array based on the delimiter.
Note: the second parameter is optional, indicating the length of the returned array
Value of string x: Hello This Is JavaScript
Separate the split(") with a space to get the array Hello,This,Is,JavaScript
Separate the split("", 2) with a space to get the array, and only keep the first two Hello,This
Replace substring
replace(search,replacement)
Find the substring search that meets the condition and replace with replacement
Note: only the first substring found is replaced by default. If you want to replace all the substrings, you need to write:
x.replace(/a/g, "o");
perhaps
var regS = new RegExp("a","g");
x.replace(regS, "o");
The g modifier is used to perform a global match (find all matches instead of stopping after the first match is found).
The array in javascript is dynamic, that is, the length can change.
There are three ways to create an array object:
- new Array() creates an array of length 0
- new Array(5); creates an array of length 5, but each element is undefine
- new Array(3,1,4,1,5,9,2,6); create array based on parameters
Method concat connects two arrays
function p(s){ document.write(s); document.write("<br>"); } var x = new Array(3,1,4); var y = new Array(1,5,9,2,6); p('array x yes:'+x); p('array y yes:'+y); var z = x.concat(y); p('Use concat Linked array x and y'); p('array z yes:'+z); //Array x is:3,1,4 //Array y is:1,5,9,2,6 //Using concat to connect arrays x and y //Array z is:3,1,4,1,5,9,2,6
Insert data and get data at the last position of the array respectively (delete after getting)
Method push pop, insert data at the last position and get data (delete after getting)
It's like a stack that comes in first and then goes out
function p(s){ document.write(s); document.write("<br>"); } var x = new Array(3,1,4); p('array x yes:'+x); x.push(5); p('towards x in push 5,obtain ' + x); var e = x.pop(); p('from x in pop A value, whose value is ' + e); p('pop After that, x The value of the array is:'+x); //Array x is:3,1,4 //push to x 5,obtain 3,1,4,5 //pop a value out of x, its value is 5 pop After that, x The value of the array is:3,1,4
Insert data at the beginning of the array and get data (delete after getting)
Method unshift shift, insert data at the beginning and get data at the beginning (delete after getting)
function p(s){ document.write(s); document.write("<br>"); } var x = new Array(3,1,4); p('array x yes:'+x); x.unshift (5); p('Pair array unshift Value 5(Add at the front),Array becomes:' + x); var e = x.shift (); p('From array shift a number(Take from the front),Its value is:' + e); p('shift After that, the array becomes:' + x); //Array x is:3,1,4 //unshift value to array5(Add at the top),Array becomes:5,3,1,4 //shift a number from an array(Take from the front),Its value is:5 shift After that, the array becomes:3,1,4
Custom sorting algorithm
Sort () uses positive sorting by default, that is, small numbers are in the front. If you need to use a custom sorting algorithm, pass the comparator function as a parameter to sort().
Comparator function:
function comparator(v1,v2){
Return v2-v1; / / v2-v1 means put the big one in front and the small one in back
}
When you call the sort function, pass the comparator function comparator as a parameter
x.sort(comparator);
Array x is: 3,1,4,1,5,9,2,6
The array x after user-defined reverse sorting with sort is: 9,6,5,4,3,2,1,1
Array de reordering
var x = new Array(3,1,4,1,5,9,2,6); var tempNum = x[0]; var result = new Array(); for( i in x){ if(-1 == result.indexOf(x[i])){ result.push(x[i]); } } result.sort(); document.write("After de reordering" + result)
Get subarray
Method slice get sub array
Note: the second parameter is not available
Array x is: 3,1,4,1,5,9,2,6
x.slice(1) gets a sub array of: 1,4,1,5,9,2,6
x. The subarray obtained by slice (1,3) is: 1,4
The second parameter is not available
Delete and insert elements
Method splice (not slice) is used to delete elements in an array
Curiously, it can also be used to insert elements into an array
Array x is: 3,1,4,1,5,9,2,6
x.splice (3,2) means to delete 2 elements from position 3: 3,1,4,9,2,6
x.splice(3,0,1,5) starts from position 3, removes 0 elements, but inserts 1 and 5, and finally obtains: 3,1,4,1,5,9,2,6
Obtain year / month / day respectively
It should be noted that the number of months returned by getMonth() is base zero, and 0 represents January
var d = new Date(); document.write('Respectively obtained on: '); document.write(d.getFullYear()); document.write("/"); document.write(d.getMonth()+1); document.write("/"); document.write(d.getDate()); //Respectively obtained on: 2020/2/23
Respectively obtained: minute: Second: millisecond
When acquired separately:branch:second:Millisecond 15:34:56:858 var d = new Date(); document.write("When acquired separately:branch:second:Millisecond "); document.write(d.getHours()); document.write(":"); document.write(d.getMinutes()); document.write(":"); document.write(d.getSeconds()); document.write(":"); document.write(d.getMilliseconds());
Day of the week
Get it through getDay(), today is the day of the week
Like getMonth(), the return value is based on 0.
//Today is: Sunday var day=new Date().getDay(); //Get the numerical day of the week from the date object var weeks = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"); document.write("Today is: "+weeks[day]);
Get the number of milliseconds since 08:00:00 on January 1, 1970
var time = new Date().getTime(); document.write("From 1970/1/1 08:00:00 Milliseconds to date: "+ time);
Date and time of modification
Modify the value of the date object to the end of the world: Wed Dec 12 2012 00:00:00 GMT+0800 (China standard time) var d=new Date(); document.write("Modify the value of the date object to the end of the world:<br>"); d.setFullYear(2012); d.setMonth(11); //Month is based on 0, so 11 means December d.setDate(12); d.setHours(0); d.setMinutes(0); d.setSeconds(0); document.write(d);
Natural logarithm and PI
Attribute E PI, representing natural logarithm and PI
document.write(Math.E); document.write("<br>"); document.write(Math.PI);
absolute value
Method abs takes absolute value
document.write(Math.abs(-1))
Methods min max is the minimum value and the maximum value respectively
1 100 document.write(Math.min(1,100)); document.write("<br>"); document.write(Math.max(1,100));
To find the n power of a number by pow
document.write(Math.pow(3,3)); //Cube of three, 27
Method round, decimal rounding
document.write(Math.round(3.4)); //3 document.write("<br>"); document.write(Math.round(3.5)); //4
Method random takes the random number between 0-1
A random number between 0-1: Math.random(): 0.186459921693092 Ten random numbers between 5 and 10: Math.round(Math.random() *5)+5
Design an object through function
Galen is killing the enemy //Timo is killing the enemy function Hero(name){ this.name = name; this.kill = function(){ document.write(this.name + "Killing the enemy<br>"); } } var gareen = new Hero("Galen"); gareen.kill(); var teemo = new Hero("Ti Mo"); teemo.kill();
Add new methods for existing objects
function Hero(name){ this.name = name; this.kill = function(){ document.write(this.name + "Killing the enemy<br>"); } } var gareen = new Hero("Galen"); gareen.kill(); var teemo = new Hero("Ti Mo"); teemo.kill(); Hero.prototype.keng = function(){ document.write(this.name + "Sinking teammates<br>"); } gareen.keng(); teemo.keng();
BOM is browser object model
Browser objects include
Window (window)
Navigator (browser)
Screen (client screen)
History (access history)
Location (browser address)
Once the page is loaded, the window object will be created automatically, so there is no need to create the window object manually. The height and width of the document display area can be obtained through the window object
document.write("Document content"); document.write("Width of the document display area"+window.innerWidth); document.write("<br>"); document.write("Height of the document display area"+window.innerHeight);
The so-called external form is browser, which may use 360, Firefox, IE, Chrome and so on.
document.write("Browser width:"+window.outerWidth); document.write("<br>"); document.write("Browser height:"+window.outerHeight);
Open a new window
Sometimes, when you come across some websites, they will automatically open another website, so how to do it?
It is achieved through the open method of window
It is not recommended to use. If a new website needs to be opened, users should be actively opened by means of hyperlinks. Opening a new website without informing users will affect users' experience
<script> function openNewWindow(){ myWindow=window.open("/"); } </script> <button onclick="openNewWindow()">Open a new window</button>
Print browser related information
document.write("<p>Browser product name:"); document.write(navigator.appName + "</p>"); document.write("<p>Browser version number:"); document.write(navigator.appVersion + "</p>"); document.write("<p>Browser internal code:"); document.write(navigator.appCodeName + "</p>"); document.write("<p>Operating system:"); document.write(navigator.platform + "</p>"); document.write("<p>Is it enabled? Cookies: "); document.write(navigator.cookieEnabled + "</p>"); document.write("<p>Browser's user agent header:"); document.write(navigator.userAgent + "</p>");
The Screen object represents information about the user's Screen
document.write("User's screen resolution: ") document.write(screen.width + "*" + screen.height) document.write("<br />") document.write("Available area size: ") document.write(screen.availWidth + "*" + screen.availHeight) document.write("<br />")
Back to last visit
<script> function goBack() { history.back(); } </script> <button onclick="goBack()">Return</button>
Back to last visit
<script> function goBack() { history.go(-2); //-1 for last time, - 2 for last time, and so on } </script> <button onclick="goBack()">Back to last</button>
reload method refreshes the current page
<span>current time:</span> <script> var d = new Date(); document.write(d.getHours()); document.write(":"); document.write(d.getMinutes()); document.write(":"); document.write(d.getSeconds()); document.write(":"); document.write(d.getMilliseconds()); function refresh(){ location.reload(); } </script> <br> <button onclick="refresh()">Refresh current page</button>
Other properties of Location
Agreement location.protocol:https: //Host name location.hostname:how2j.cn //Port number (The default is80,No means no80port)location.port: //location of host plus terminal.host: how2j.cn //Access path location.pathname: /k/javascript/javascript-bom-location/451.html //Anchor location.hash: //Parameter list location.search: <script> function p(s){ document.write(s); document.write("<br>"); } p("Agreement location.protocol:"+location.protocol); p("host name location.hostname:"+location.hostname); p("Port number (The default value is 80. If not, it means 80 port)location.port:"+location.port); p("Host plus terminal slogan location.host: "+location.host); p("Access path location.pathname: "+location.pathname); p("Anchor point location.hash: "+location.hash); p("parameter list location.search: "+location.search); </script>
Warning box alert
It is often used for message prompt, such as successful registration, etc
<script> function register(){ alert("login was successful"); } </script> <br> <button onclick="register()">register</button>
confirm box
It is often used to confirm the dangerous operation. For example, when deleting a record, a confirmation box will pop up
confirm returns the Boolean true or false of the basic type
<script> function del(){ var d = confirm("do you want to delete?"); alert(typeof d + " " + d); } </script> <br> <button onclick="del()">delete</button>
The input box prompt is used to pop up an input box for the user to input relevant information
Because the pop-up interface is not good-looking, it is likely to be inconsistent with the style of the website, so it is rarely used in actual work
<script> function p(){ var name = prompt("enter one user name:"); alert("The user name you entered is:" + name); } </script> <br> <button onclick="p()">enter one user name</button>
timer
setTimeout is only executed once
setInterval repeatedly
clearInterval terminate duplicate execution
document.write() do not use document.write() in the function called by setInterval;
Only once
Function setTimeout(functionname, milliseconds from the start time);
Function name is executed once after the specified number of milliseconds through setTimeout
This example prints the current time after 3 seconds.
Interpretation:
document.getElementById get div element with id=time
. innerHTML modify the content of this element
<script> function printTime(){ var d = new Date(); var h= d.getHours(); var m= d.getMinutes(); var s= d.getSeconds(); document.getElementById("time").innerHTML= h+":"+m+":"+s; } function showTimeIn3Seconds(){ setTimeout(printTime,3000); } </script> <div id="time"></div> <button onclick="showTimeIn3Seconds()">After clicking3Display the current time in seconds and only once</button>
Keep repeating
Function setinterval (function name, number of milliseconds between repeated executions);
Repeat the same function through setInterval at a time interval specified by the second parameter
<p>every other1Seconds, print current time</p> <div id="time"></div> <script> function printTime(){ var d = new Date(); var h= d.getHours(); var m= d.getMinutes(); var s= d.getSeconds(); document.getElementById("time").innerHTML= h+":"+m+":"+s; } var t = setInterval(printTime,1000); </script>
Terminate a recurring task with clearInterval
demo is as follows: when the second is a multiple of 5, execution stops
<p>every other1Seconds, print current time</p> <div id="time"></div> <script> var t = setInterval(printTime,1000); function printTime(){ var d = new Date(); var h= d.getHours(); var m= d.getMinutes(); var s= d.getSeconds(); document.getElementById("time").innerHTML= h+":"+m+":"+s; if(s%5==0) clearInterval(t); } </script>
Don't use document.write() in the function called by setInterval; some browsers, such as firefox, have this problem, but others don't.
Suppose that the function called by setInterval is printTime, calling document.write() in printTime;
You can only see the effect of printing time once.
This is because document.write will create a new document. In the new document, there are only time strings printed out, and there are no javascript calls such as setInterval, so you will only see the effect of execution once.
<p>every other1Seconds, through document.write Print current time</p> <script> function printTime(){ var d = new Date(); document.write(d.getHours()); document.write(":"); document.write(d.getMinutes()); document.write(":"); document.write(d.getSeconds()); document.close(); } var t = setInterval(printTime,1000); </script>