javascript knowledge summary

1.JS usage:

A. Tag: < script > < / script >

B. Tags can be placed in the head or body. When in the body, the script should be placed at the bottom of the < body > element to improve the display speed, because Script Compilation will slow down the display.

C. Default attribute: < script type = "text / JavaScript" >, but the type attribute is not required. JavaScript is the default scripting language in HTML.

D. External introduction: < script SRC = "myscript. JS" > < / script >

2.JS output:

A. Use innerHTML

<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;//Insert content
</script>

B. use document write(). However, it should be noted that this is generally used for testing

<script>
document.write(5 + 6);
</script>

C. Use console log(). Generally used for console display

<script>
console.log(5 + 6);
</script>

D. Use window alert(). A warning window will pop up You can also use windows

<script>
window.alert('Study hard');
</script>

design sketch:

3.JS variable naming

A. All JavaScript identifiers are case sensitive.

For example, variables , LastName , and , LastName , are two different variables.

B. underline nomenclature:

For example: qian_duan

C. Hump nomenclature:

For example: FirstName, LastName, MasterCard, InterCity That is, start with the capital of the word and then connect it

But JavaScript programmers tend to use hump case that begins with a lowercase letter For example: getElementById

D. During programming, there are multiple variables in one line: var person = "Bill Gates", carName = "porsche", price = 15000;

4.JS notes

A. Single line comment: / /

B. / *, multiline comment:*/  

 5. let and const. In JS

A. In JS, var has no block scope. Variables declared within block {} can be accessed from outside the block. Using the var keyword to redeclare variables can cause problems. Redeclare variables using the let keyword can solve this problem. Redefining variables in a block does not redeclare variables outside the block

var x = 10;
// Where x is 10
{ 
  let x = 6;
  // Where x is 6
}
// Where x is 10

B. const , defines a variable similar to , let , but cannot be reassigned For example:

const PI=3.14159.

C. Use typeof to return the type of the variable.

D.x ** y produces the same results as math Pow (x, y) is the same:

 6. Data type of JS

JavaScript variables can hold a variety of data types: numeric values, string values, arrays, objects, and so on:

var length = 7;                             // number
var lastName = "Gates";                      // character string
var cars = ["Porsche", "Volvo", "BMW"];         // array
var x = {firstName:"Bill", lastName:"Gates"};    // object

7.JS function

Function name (parameter 1, parameter 2, parameter 3) 
{
    Code to execute
 return parameter
}

8.JS object

If you declare a JavaScript variable with the keyword "new", the variable is created as an object

var x = new String();        // Declare x as a String object
var y = new Number();        // Declare y as a Number object
var z = new Boolean();       //	Declare z as a Boolean object

9.JS object

The following are common JS objects:

  

10.JS string

A. You can use single or double quotation marks for reference

var study="qianduanxuexi" or var study='qianduanxuexi '

B. The built-in attribute length returns the length of the string For example, study length

C. Special characters:

D. Escape character:

E. For best readability, programmers usually avoid more than 80 strings per line of code. You can wrap a line in a string with a backslash For example:

document.getElementById("demo").innerHTML = "Hello \
Kitty!";

 11. String method

A. The length property returns the length of the string

B. The indexof () method returns the index (position) of the first occurrence of the specified text in the string

var str = "The full name of China is the People's Republic of China.";
var pos = str.indexOf("China");

C. The lastindexof() method returns the index of the last occurrence of the specified text in the string

var str = "The full name of China is the People's Republic of China.";
var pos = str.lastIndexOf("China");

D.slice() method:

slice() extracts a part of the string and returns the extracted part in the new string.

var str = "Apple, Banana, Mango";
var res = str.slice(7,13);

E. The replace () method replaces the value specified in the string with another value

str = "Please visit Microsoft and Microsoft!";
var n = str.replace("Microsoft", "W3School");

12.JS string template

A. Template literals provide a simple way to insert variables and expressions into strings.

Template literals use backquotes (` `) instead of quotation marks ("") to define strings

${...}
let firstName = "John";
let lastName = "Doe";
let text = `Welcome ${firstName}, ${lastName}!`;
Internet Explorer does not support template literals.

B. ToFixed (function)

Adding a knowledge function after a variable will retain several decimal places    

13.JS digital

A.var x = 123e5; // 12300000      var y = 123e-5; // 0.00123

B can use the global JavaScript function {isNaN() to determine whether a value is a number

Note: NaN # is a number, and typeof NaN # returns # number

C.Infinity (or - infinity) is the value returned by JavaScript when it exceeds the maximum possible number when calculating the number.

var x = 2 / 0; // x will be Infinity var y = - 2 / 0// Y will be - Infinity

D.Infinity # is a number: typeOf Infinity # returns # number.

14. const. Of JS

A. Arrays declared with , const , cannot be reassigned

B.JavaScript , const , variables must be assigned values when declared: this means that arrays declared with , const , must be initialized when declared. Using const without initializing the array is a syntax error

 

15.JS digital method

A. Return as string myNumber. ToString (hexadecimal number) returns a numeric value.

B.toExponential() returns a string value

var x = 9.656;
x.toExponential(2);     // Return to 9.66e+0
x.toExponential(4);     // Return to 9.6560e+0
x.toExponential(6);     // Return to 9.656000e+0

C.toFixed() returns a string value that contains a number with a specified number of decimal places

var x = 9.656;
x.toFixed(0);           // Return to 10
x.toFixed(2);           // Return to 9.66
x.toFixed(4);           // Return to 9.6560
x.toFixed(6);           // Return to 9.656000

 16.JS array method

A. The JavaScript method toString() converts an array into a string of array values (comma separated).

var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString(); 

B. The pop () method deletes the last element from the array

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();              //  Remove the last element ("Mango") from fruits

C. The push () method (at the end of the array) adds a new element to the array:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");       //  Add a new element to fruits

16.JS string

A. Template literals use backquotes (` `) instead of quotation marks ("") to define strings

let firstName = "John";
let lastName = "Doe";
Ilet text = `Welcome ${firstName}, ${lastName}!`;

17.JS array

A.

JavaScript variables can be objects. Arrays are special types of objects. Because of this, we can store different types of variables in the same array. You can save objects in an array. You can save functions in an array. You can even save an array in an array

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;

B. you can also add new elements to the array using the length attribute

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon";     //  Add a new element to fruits (Lemon)

C. In JavaScript, arrays use numeric indexes. In JavaScript, objects use named indexes.

D. The JavaScript operator "typeof" returns "object"

var fruits = ["Banana", "Orange", "Apple", "Mango"];

typeof fruits;             // Return object

The typeof operator returns "object" because the JavaScript array belongs to an object.

To solve this problem, ECMAScript 5 defines a new method called array isArray().

Array.isArray(fruits);     // Return true

 18.JS array sorting

A. The sort () method sorts the array alphabetically

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();            // Sort the elements in fruits

B. You can use the reverse() method to reverse the elements in the array, and you can use it to sort the array in descending order

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();            // Sort the elements in fruits
fruits.reverse();         // Reverse element order

C. Digital arrangement

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;  

function myFunction() {
  points.sort(function(a, b){return a - b});//a-b is from small to large, and b-a is from large to small
  document.getElementById("demo").innerHTML = points;
}
</script>

D.JS date

var d = new Date();

E. The gettime () method returns the number of milliseconds since January 1, 1970

var d = new Date();
document.getElementById("demo").innerHTML = d.getTime();

F. The getFullYear () method returns the date year as a four digit number

var d = new Date();
document.getElementById("demo").innerHTML = d.getFullYear();

H.getMonth() returns the month of the date in numbers (0-11)

var d = new Date();
document.getElementById("demo").innerHTML = d.getMonth();

1. The getdate () method returns the day of the date as a number (1-31)

The getHours() method returns the number of hours of the date in numbers (0-23):

The getMinutes() method returns the number of minutes of the date in numbers (0-59)

The getSeconds() method returns the number of seconds of the date in numbers (0-59)

The getMilliseconds() method returns the number of milliseconds of the date as a number (0-999)

The getDay() method returns the weekday of the date in numbers (0-6)

19. JS mathematics

A.Math.PI;

B.Math. The return value of round (x) is x rounded to the nearest integer

Math. The return value of ceil (x) is the nearest integer rounded on X +

Math. The return value of floor (x) is the nearest integer rounded down by X +

Math.round(6.8);    // Return to 7
Math.round(2.3);    // Return 2

C.Math. The return value of pow (x, y) is the Y power of X

Math.pow(8, 2);      // Return 64

D.Math.sqrt(x) returns the square root of X

Math.sqrt(64);      // Return 8

E.Math.abs(x) returns the absolute (positive) value of X

F.Math.min() and {math Max() can be used to find the lowest or highest value in the parameter list

Math.min(0, 450, 35, 10, -8, -300, -78);  // Return - 300
Math.max(0, 450, 35, 10, -8, -300, -78);  // Return 450

G.Math.random() returns a random number between 0 (inclusive) and 1 (exclusive)

Math.floor(Math.random() * A); 	//  Returns the number between 1 and A-1

20.JS logic

JavaScript Boolean (logic) represents one of two values: true or false

You can use the Boolean() function to determine whether an expression (or variable) is true

The Boolean value of 0 (zero) is false

-The Boolean value of 0 (negative zero) is false

The Boolean value of '' (null value) is false

The Boolean value of undefined , is , false

The Boolean value of null is false

The Boolean value of NaN , is , false

 21.JS comparison

variablename = (condition) ? value1:value2
var voteable = (age < 18) ? "Too young": "mature enough"

<!DOCTYPE html>
<html>
<body>

<p>Enter your age and click this button:</p>

<input id="age" value="18" />

<button onclick="myFunction()">have a try</button>

<p id="demo"></p>

<script>
function myFunction() {
  var age, voteable;
  age = document.getElementById("age").value;
  voteable = (age < 18) ? "So young":"Mature enough";
  document.getElementById("demo").innerHTML = voteable;
}
</script>

</body>
</html>

21.JS conditions

if (condition) {
    Condition is true Code block executed at
} else { 
    Condition is false Code block executed at
}

if (Condition 1) {
    Condition 1 is true Code block executed at
} else if (Condition 2) {
    Condition 1 is false And condition 2 is true Code block executed at
 } else {
    Condition 1 and condition 2 are both false Code block executed at
}
switch(expression) {
     case n:
        Code block
        break;
     case n:
        Code block
        break;
     default:
        Default code block
} 

22. For in cycle of JS

A. The JavaScript for in statement loops through the properties of the object

const person = {fname:"John", lname:"Doe", age:25};
let text = "";
for (let x in person) {
  text += person[x];
}

const numbers = [45, 4, 9, 16, 25];
let txt = "";
for (let x in numbers) {
  txt += numbers[x];
}

B. The JavaScript for statement loops through the values of the iteratable object.

const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
  text += x;
}

Internet Explorer does not support For/of.

let language = "JavaScript";
let text = "";
for (let x of language) {
text += x;
}

23. typeof type of JS

A. There are five different data types in JavaScript that can contain values:

  • string
  • number
  • boolean
  • object
  • function

There are six types of objects:

  • Object
  • Date
  • Array
  • String
  • Number
  • Boolean

And 2 data types that cannot contain values:

  • null
  • undefined

B. you can use the {typeof} operator to determine the data type of JavaScript variables.

typeof "John"                 // Return "string"
typeof 3.14                   // Return to "number"
typeof NaN                    // Return to "number"
typeof false                  // Return "boolean"
typeof [1,2,3,4]              // Return to "object"
typeof {name:'John', age:34}  // Return to "object"
typeof new Date()             // Return to "object"
typeof function () {}         // Return to "function"
typeof myCar                  // Return "undefined"*
typeof null                   // Return to "object"

 24.JS arrow function

Arrow functions can write shorter code

hello = () => {
  return "Hello World!";
}

24.JS regular representation

/ w3school/i , is a regular expression.

w3school # is a pattern (used in search).

i , is a modifier (change the search to case insensitive).

<script>
var str = "Visit W3School!"; 
var n = str.search(/w3School/i);
document.getElementById("demo").innerHTML = n;
</script>

 25.JS exception

The try} statement allows you to define a block of code to detect errors at execution time.

The catch statement allows you to define a code block to execute if an error occurs in the try code block.

JavaScript statements , try , and , catch , appear in pairs:

try {
     Code blocks for testing
}
 catch(err) {
     Code block handling errors
} 

Keywords: Javascript Front-end elementUI

Added by megavolt on Wed, 09 Mar 2022 18:18:15 +0200