How to quickly get started with VUE3.0: Enter and learn
related recommendations: JavaScript Tutorial
that runs in the client browser. Every browser has a JavaScript parsing engine script language: it does not need to be compiled, it can be directly parsed and executed by the browser. It can enhance the interaction process between users and HTML pages, control HTML elements, and make the page dynamic. effect and enhance the user experience
In 1992, Nombase developed the first client-side scripting language, specifically used for form verification. Named: C--, later renamed: ScriptEase
In 1995, Netscape developed a client-side scripting language: LiveScript. Later, experts from SUN were invited to modify LiveScript and name it JavaScript
In 1996, Microsoft copied JavaScript and developed the JScript language.
In 1997, ECMA (European Computer Manufacturers Association) formulated a standard for client-side scripting languages: ECMAScript, which unifies the encoding methods of all client-side scripting languages.
JavaScript = ECMAScript + JavaScript’s own unique things (BOM+DOM)
a. Interpreted language
b. Object-based
c.Event driven
d.Weak type
e. High safety
f. Cross-platform
If you need to insert JavaScript into the HTML page, please use the <script>
tag.
<script> 和</script>
tell JavaScript where to start and end.
The lines of code between <script> 和</script>
contain JavaScript
<script type="text/javascript" src="${request.contextPath}/static/js/homepage.js"></script>
window.alert()document.write()innerHTML console.log()
From personal use, console.log()
is more convenient to use in programming. You can directly view the output content through the F12 console.
// This is the code: a single sentence comment, usually the ctrl + L key in the editor.
/* This is the code*/: Multi-line comments, usually ctrl + shift + L keys in the editor.
// Declare a variable named test. var test;
var age, name, sex;//Declare three variables of age, name, and sex
//Declare variables at the same time and assign values var age = 10, name = "Xiaoqiang", sex = "1";
1. It consists of letters, numbers, underscores, and symbols. It cannot start with a number.
2. Keywords cannot be used, for example: while
3. Case-sensitive specifications: conventional writing method
1. Variable names must be meaningful.
2. Comply with the camel case nomenclature. The first letter of the camel case nomenclature is lowercase, and the first letter of the following words is capitalized, such as userName.
The data types include: Number类型、String类型、Boolean类型、Undefined类型、Null类型、Object类型
Number digital type: includes integers and decimals and can be expressed in: decimal, octal, hexadecimal,
such as:
var num = 10; //Decimal var num1 = 012; //Octal var num2 = ox123; //Hexadecimal
value range:
console.log(Number.MAX_VALUE); //The maximum value is 5e-324console.log(Number.MIN_VALUE); //The minimum value is 1.7976931348623157e+308 Infinity: Infinity: -Infinity
numerical judgment cannot use decimals to verify decimals and do not use NaN to verify whether it is NaN (NaN----not a number) but you can use isNaN— is not Is the result of a number NaN?
Such as:
var num; //Declare a variable, unassigned console.log(isNaN(num)); // Isn't true a number? The result is true
string escape character:
escape sequence | character |
---|---|
bbackspace | |
fpaper | feed |
nline | feed |
rcarriage | return |
thorizontal tab (Ctrl-I) | |
' | single quote |
" | Double quotes |
double slashes |
eg:
var str = "iam a pm\"console.log(str); // iam a pm
String concatenation:
var str1 = "Mr.";var str2 = "Hello";console.log(str1+str2); // Hello sir,
if the result of splicing strings and numbers is also the effect of string splicing as shown above
Boolean Boolean type, the two attributes true/false
Undefined undefined means a variable that has been declared without assignment, the variable When only declared, the value defaults to undefined.
For example:
var num;console.log(num); // undefined
Null represents a null. If the value of the variable is to be null, it must be set manually
(1), Number() Any value can be converted into a numeric value. If there is a character in the string to be converted that is not a numeric value, NaN is returned.
For example:
var num1 = Number("10");console.log(num1); // 10var num2 = Number('10adbdn');console.log(num2); //NaNvar num3 = Number("10.78");console.log(num3); //10.78var num4 = Number('10.65dd');console.log(num4); //NaNvar num5 = Number("a10");console.log(num5); //NaN
(2), parseInt() converts to integer such as:
var num1 = parseInt("10");console.log(num1); // 10var num2 = parseInt('10adbdn');console.log(num2); //10var num3 = parseInt("10.78");console.log(num3); //10var num4 = parseInt('10.65dd');console.log(num4); //10var num5 =parseInt("a10");console.log(num5); //NaN
(3), convert parseFloat() to decimal, such as:
var num1 = parseFloat("10");console.log(num1); // 10var num2 = parseFloat('10adbdn');console.log(num2); //10var num3 = parseFloat("10.78");console.log(num3); //10var num4 = parseFloat('10.65dd');console.log(num4); //10var num5 = parseFloat("a10");console.log(num5);
The difference between (4), Number(), parseInt(), and parseFloat()
Number() is stricter than parseInt() and parseFloat().
parseInt() is similar to parseFloat(), parseFloat will parse the first one. When encountering the second one or non-number end
(1), toString()
For example:
var num = 10;console.log(num.toString()); // String 10
(2), String()
For example:
var num1 =5;console.log(String(num1)); // String 5
(2), JSON.stringfy()
0, empty string, null, undefined, NaN will be converted to false, others will be converted to true
For example:
var num1 = Boolean(0);console.log(num1); // falsevar num2 = Boolean("");console.log(num2); // falsevar num3 = Boolean(null);console.log(num3); / falsevar num4 = Boolean(undefined);console.log(num4); // falsevar num5 = 10;var num6;console.log(Boolean(num5+num6)); / false
Operator types: arithmetic operators, compound operators, relational operators, logical operators
(1), arithmetic operators: "+" "-" "*" "/" "%"
Arithmetic expressions: expressions connected by arithmetic operators. Compound operations
(2). Compound operators: "+=""-=""*=""/=""%="
Compound operation expressions: Expressions (3) connected by compound operators
, relational operators: ">""<"">=""<="" "" =""!=""!== "
Relational operation expression: expressions connected by relational operators
Logical operation expression:(4), logical operators: "&&" "||" "!"
Expression 1 && Expression 2
connected by logical operators
If one of them is false, the entire result is false.
Expression 1 || Expression 2
If one of them is true, the entire result is false
! The result of the expression expression is true, and the entire result is false.
The result of the expression is false, and the entire result is true
is from high to low:
() The highest priority unary operator ++ – !
The arithmetic operators are * / % and then + -
Relational operators > >= < <=
Equality operator == != === !==
Logical operators are && followed by ||
Assignment operator
Functions in JavaScript are objects. An object is a collection of name/value pairs and has a hidden connection to the prototype object. The object produced by the object literal is connected to Object.prototype. Function objects are connected to Function.prototype (which itself is connected to Object.prototype). Each function will have two hidden attributes attached when it is created: the context of the function and the code that implements the function's behavior
function functionname() {here is the code to be executed}
Syntax:
Parentheses can include arguments separated by commas:
(argument1, argument2, …)
Code executed by the function is placed within curly braces: {}
function name(argument1, argument2, argument3) { Code to be executed}
Function parameters are the names listed in the function definition.
Function arguments are the actual values received by the function when the function is called.
Call of the function:
//Create a function sumfunction here sum(num1, num2) { var result = num1 + num2; console.log("num1 + num2 = " + result);}// Function call sum(10, 20);
execute the function immediately:
$(function(){ //Not just functions, all variable outputs, etc. written here are page loads and run directly sum()})2.7.
literals. Syntax: Reg = /pattern/modifiers;
the literal regularity consists of two forward slashes//, and the rule is written after the first forward slash: /pattern[Rules can write various metacharacters | quantifiers | words set|assert...]. After the second forward slash, write the identifier /modifiers [g global match | i ignore case | m newline match | ^ starting position | $ ending position] identifier.
var Reg = /box/gi;
Constructor. Syntax Reg = new RegExp( pattern , modifiers );
pattern, modifiers are strings at this time. No matter how you create it, it is the same, pattern template, content to match, and modifiers.
var Reg = new RegExp("box","gi");
method | description in |
---|---|
String String.match(Reg) | returns an array containing all strings matched by RegExp or null |
String.search(Reg ) | Returns the position where the RegExp matching string first appears |
String.replace(Reg, newStr) | Replaces the RegExp matching result with newStr and returns the new string |
String.split(Reg) | Returns an array in which the string is split according to the specified RegExp |
var str = ' a1b2c3a4a5', reg = /a/g;console.log(str.match(reg)); //["a", "a", "a"]var str = 'a1b2c3a4a5', reg = /a/;console.log(str.search(reg)); //0var str = 'a1b2c3a4a5', reg = /a/g;console.log(str.replace(reg,function(){ console.log(arguments); return 5555;}));var str = 'a,b,c,d', reg = /,/g;//console.log(str.split(',')); //["a", "b", "c", "d"]console.log(str.split( reg)) //["a", "b", "c", "d"]
RegExp.exec | ( |
---|---|
String) | performs a matching search in the string and returns the first matching result Array |
RegExp.test(String) | tests pattern matching in a string and returns true or false |
Modifiers are also called identifiers and can specify matching patterns. Modifiers are used to perform case-sensitive and global matching. .
iignore case matching.
g matches globally. Without g, only the first element is matched, and no matching is performed.
m performs multi-line matching
var patt = /pattern/i; //Ignore case matching var patt = /pattern/g; //Global matching var patt = /pattern/m; //Perform multi-line matching
are special characters that have special meaning in regular expressions.
Special translation characters. /.
. A single character, except newline n and tab r Escape character, escape symbols with special meaning into ordinary symbols: .d Numbers [0~9]D Non-numberss SpacesS Non-spacesw Characters [letters|digits|underscore]W Non-character b word boundary (except (word) alphanumeric_ are all word boundaries) B non-word boundary
var reg = /./;//match.var reg = /\/;//match var reg = ///;//Match /var str = '\';var reg = /\/g;console.log(reg.test(str)); //true
A Date object is an object related to date and time. It is dynamic and you must use the new keyword to create an instance, such as:
var Mydata=new Date();
The Date object does not provide direct access properties, only methods to get and set the date, as shown in the following table
The String object is a string processing object provided by JavaScript. It can be referenced only after creating an object instance. It provides properties and methods for processing strings (similar to Java). The details are as follows:
Property length —Returns the number of characters in the string.
Note: A Chinese character is also a character! !
properties:
Math object methods:
Trigonometric functions (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) return values in radians. You can convert radians to degrees by dividing Math.PI / 180, or by other methods.
Method | Description |
---|---|
Math.abs(x) | returns the absolute value of x. |
Math.acos(x) | returns the inverse cosine of x. |
Math.acosh(x) | returns the inverse hyperbolic cosine of x. |
Math.asin(x) | returns x The arcsine of x. |
Math.asinh(x) | returns the inverse hyperbolic sine of x. |
Math.atan(x) | returns the arctangent of x as a number between -PI/2 and PI/2 radians. |
Math.atanh(x) | returns the inverse hyperbolic tangent of x. |
Math.atan2(x, y) | returns the arctangent of y/x. |
Math.cbrt(x) | returns the cube root of x. |
Math.ceil(x) | returns The value of x rounded up. |
Math.clz32(x) | Returns the number of leading zeroes of a 32-bit integer. |
Math.cos(x) | returns the cosine of x. |
Math.cosh(x) | returns the hyperbolic value of x Cosine value. |
Math.exp(x) | returns Ex, when x is an argument and E is Euler's constant (2.718…), the base of natural logarithms. |
Math.expm1(x) | returns the value of exp(x)-1. |
Math .floor(x) | returns the largest integer less than x. |
Math.fround(x) | Returns the nearest single precision float representation of a number. |
Math.hypot([x[,y[,…]]]) | Returns the square root of the sum of squares of its arguments. |
Math.imul( x) | Returns the result of a 32-bit integer multiplication. |
Math.log(x) | Returns the natural logarithm (loge, also ln) of a number. |
Math.log1p(x) | Returns the natural logarithm of 1 + x (loge, also ln) of a number. |
Math.log10(x) | Returns the base 10 logarithm of x. |
Math.log2(x) | Returns the base 2 logarithm of x. |
Math.max([x[,y[,…]]] ) | returns the maximum value from 0 to multiple values. |
Math.min([x[,y[,…]]]) | returns the minimum value from 0 to multiple values. |
Math.pow(x,y) | returns the value of x y power. |
Math.random() | returns a pseudo-random number between 0 and 1. It may be equal to 0, but it must be less than 1. |
Math.round(x) | returns a rounded integer. But the value of Math.round(-4.40) is -4 |
Math.sign(x) | returns the sign function of x, which determines whether x is positive, negative or 0. |
Math.sin(x) | returns the sine value. |
Math.sinh(x) | returns the hyperbolic sine value of x. |
Math.sqrt (x) | returns the square root of x. |
Math.tan(x) | returns the tangent of x. |
Math.tanh(x) | returns the hyperbolic tangent of x. |
Math.toSource() | returns the string "Math". |
Math.trunc( x) | Returns the integer part of x, removing the decimals. |
Example 1: Write a function that returns a random integer from min to max, including min but excluding max
function getRandomArbitrary(min, max) { return min + Math.random() * (max - min);}
Example 2: Write a function to generate a random string of length n. The value range of the string characters includes 0 to 9, a to z, A to Z
function getRandomInt(min, max) { return min + Math.floor(Math.random() * (max - min + 1));}function randomStr(n){ var dict = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; var str = ''; for(i = 0; i < n;i++){ str += dict[getRandomInt(0,62)]; } return str;}var str = getRandStr(10);console.log(str);2.8.4.
Classification of
1. Two-dimensional array. The essence of a two-dimensional array is that the elements in the array are also arrays.
2
of column 2 and row 1 of a.Sparse array
. A sparse array contains values starting from 0 The starting non-contiguous index of the array. In sparse arrays, the length attribute value is generally larger than the actual number of elements (uncommon)
Example
var a=["a",,"b",,,,"c",,];
Array object attribute
Attribute | function |
---|---|
The length attribute | represents the length of the array, that is, the number of elements in it. |
The prototype attribute | returns a reference to the prototype of the object type. |
The constructor attribute | represents the function that creates the object |
1.length attribute:
alert(arr.length); //Display the length of the array 10arr.length=15; //Increase the length of the array, the length attribute is variable alert(arr.length ); //Shows that the length of the array has become 15
2.prototype attribute
The prototype attribute returns a reference to the prototype of the object type. The prototype property is common to objects.
objectName.prototype
The objectName parameter is the name of the object object.
Description: Use the prototype attribute to provide a set of basic functions of the object's class. New instances of an object "inherit" the operations assigned to the object's prototype.
For array objects, use the following example to illustrate the use of the prototype attribute.
Add a method to the array object that returns the maximum element value in the array. To accomplish this, declare a function, add it to Array.prototype, and use it.
function array_max( ){ var i, max = this[0]; for (i = 1; i < this.length; i++){ if (max < this[i]) max = this[i]; } return max;}Array.prototype.max = array_max;var x = new Array(1, 2, 3, 4, 5, 6);var y = x.max( );
3.constructor attribute
The constructor attribute represents the created object function.
object.constructor //object is the name of the object or function.
Description: The constructor attribute is a member of all objects with prototype. They include all JScript native objects except Global and Math objects. The constructor attribute holds a reference to the function that constructs a specific object instance.
For example:
x = new String("Hi");if (x.constructor == String) // Process (condition is true). //or function MyFunc {// Function body. }y = new MyFunc;if (y.constructor == MyFunc) // Process (condition is true).
Array object method <br/> Description: Part of it is a new feature of ECMAScript5 (not supported by IE678).
The method | function |
---|---|
concat() | connects two or more arrays and returns the result. |
join() | combines the elements of the array into a string. |
pop() | deletes and returns the last element of the array |
push() | adds one or more elements to the end of the array and returns the new length |
reverse | reverses the order of the elements in the array |
shift() | deletes and returns the first element of the array |
slice() | starts from An existing array returns the selected elements |
sort() | sorts the array elements |
splice() | deletes elements and adds new elements to the array |
toSource() | returns the source code of the object |
toString() | converts the array into a string and returns result |
toLocalString() | converts the array into local elements and returns the result |
unshift | adds one or more elements to the beginning of the array and returns the new length |
valueof() | returns the original value of the array object |
forEach() | traverses the array object |
map() | pairs the array Do some mapping |
filter() | filter |
every() | check and judge |
some() | check and judge |
reduce() | perform certain operations in pairs |
reduceRight() | perform operations from right to left |
indexOf() | array retrieval to find a certain element |
Array.isArray ([] ) | Determining whether it is an array |
mainly explains some new features
concat
The function of concat is to splice arrays. It should be noted that an array element can also be used as a spliced element. In this case, the array will be flattened and then spliced with other elements to form a new array, but it will not be flattened twice. concat does not modify the original array.
For example:
var arr=[1,2,3,4,5];arr.concat([10,11],13);//[1,2,3,4,5,10,11,13]arr .concat([1,[2,3]]);//[1,2,3,4,5,1,[1,3]]
slice
slice (a, b) a and b can take negative numbers, which means that an array is intercepted from position a to position b. It is an interval that is closed on the left and open on the right. A and b can take negative numbers. If it is a negative number, it means the last a/ b elements
var arr=[1,2,3,4,5];arr.slice(1,3);//[2,3]arr.slice(1);//[2,3,4, 5]arr.slice(1,-1);//[2,3,4]arr.slice(-4,-3);//[2]
splice
splice removes elements and adds new elements to array
object.splice(a) deletes a elements from the left
object.splice(a, b) intercepts b elements starting from position a
object.splice(a, b, c, d) intercepts b elements starting from position a, and inserts c and d or more elements into the original array. It should be noted that splice will modify the original array
var arr=[1,2 ,3,4,5];arr.splice(2);//[3,4,5]arr;//[1,2];The original array has been modified var arr=[1,2,3,4 ,5];arr.splice(2,2);//[3,4]arr;//[1,2,5];var arr=[1,2,3,4,5];arr.splice (1,1,'a','b');//[2]arr;//[1,"a","b",3,4,5];
foreach
The foreach() function traverses the array from beginning to end. There are three parameters: array elements, index of elements, and the array itself
var arr = [1, 2, 3, 4, 5]; arr.forEach(function(x, index, a){//Corresponding to: array elements , the index of the element, the array itself console.log(x + '|' + index + '|' + (a === arr));});// 1|0|true// 2|1|true/ / 3|2|true// 4|3|true// 5|4|true
reduce()
Array's reduce() applies a function to [x1, x2, x3...] of this Array. This function must receive two parameters. reduce() continues the result and performs a cumulative calculation with the next element of the sequence. The effect is :
[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)
var arr = [1, 2, 3];var sum = arr.reduce( function(x, y) { return x + y}, 0); //Parameter 0 is optional. If parameter 0 is written, the two values passed for the first time are 0 and 1. If not, the first two values passed for the first time are the first two values of the array. value, the calculation result is 6arr; //[1, 2, 3]arr = [3, 9, 6];var max = arr.reduce(function(x, y) { console.log(x + "|" + y); return x > y ? x : y;});// 3|9// 9|6max; //
Comparison of 9 arrays and general objects
Arrays and general objects | ||
---|---|---|
can be inherited | in the same way | . The object does not have to be an array, but can be treated as an object to add attributes.|
array | automatically updates length. Accessing arrays by index is significantly faster than accessing general object attributes.Array objects inherit a large number of array operation methods on Array.prototype. |
Comparison of arrays and strings
arrays and strings. | |
---|---|
Strings | are a kind of |
difference | between arrays.Strings are immutable arrays. Strings do not have array methods. |
is used to serialize js objects into JSON strings.
var person={name:"xiaoming",age:12}var json=JSON.stringify(person); //{"name":"xiaoming","age":12}
In addition to accepting objects, stringify()
You can also accept 2 parameters. The first parameter is a filter, which can be an array collection of object properties or a function; the second parameter is an option indicating whether to retain the indented
array filter in the JSON string:
json=JSON.stringify(person,['name']); //{"name":"xiaoming"}
Function filter:
json=JSON.stringify(person,function(key,value){ switch(key){ case "name": return value+",wang"; case "age": return undefined; default: return value; }});//{"name":"xiaoming,wang"}
Note that if the function returns undefined, this attribute will be ignored;
string indentation:
json=JSON.stringify(person,null,4); { "name": "xiaoming", "age": 12}
Add toJSON() method to the object:
var person={ name:"xiaoming", age:12, toJSON:function(){ return this.name+" is "+this.age; }}json=JSON.stringify(person);console.log(json); //"xiaoming is 12"
In addition to accepting a json string, parse() can also accept a function parameter. This function accepts 2 values, a key and a value;
var person=JSON.parse('{"name":"xiaoming","age":12}');var person=JSON.parse('{"name ":"xiaoming","age":12}',function(key,value){ if(key=="age"){ return value+10; } else{ return value; }});
1. Create an XMLHttpRequest asynchronous object
2. Set the request method and request address
3. Next, use send to send the request
4. Monitor status changes
5. Finally, receive the returned data.
Example:
const xhr = new XMLHttpRequest()xhr.open('GET', './data/test.json', true)xhr.onreadystatechange = function () { if (xhr. readyState === 4) { if (xhr.status === 200) { console.log(JSON.parse(xhr.responseText)) } else { console.log('Other situations...') } }}xhr.send()
$.ajax({ type: "post", //Request method url: "a.php", //The link address of the server dataType: "json", //The format of transmitting and receiving data data:{ username:"james", password:"123456" }, success:function(data){//Function console.log(data) called when receiving data successfully;//data is the data returned by the server}, error:function(request){//The function called when requesting data fails alert("An error occurred:"+request.status); }});
structure
$.get(url, [data], [callback], [type])
Parameter explanation:
//Step 1: Create an asynchronous object var ajax = new XMLHttpRequest(); //Step 2: Set the url parameters of the request. The first parameter is the type of request, and the second parameter is the requested urlajax.open("get", " users.json");//Step 3: Send a request ajax.send();//Step 4: Register the event onreadystatechange. When the state changes, ajax.onreadystatechange = function () { if (ajax.readyState == 4 && ajax.status == 200) { //Step 5: If you can enter this judgment, it means that the data has returned perfectly, and the requested page exists console.log(ajax.responseText); //Enter the content of the response}};
It has the same structure and usage as the $.get() method, but there are still some differences between them.
1. Post is safer than get; if requested in get mode, the request parameters will Spliced to the back of the URL, the security is low. When requesting in post mode, the request parameters will be wrapped in the request body, which is more secure.
2. Difference in quantity: The amount of data transmitted by the get method is small and cannot exceed 2kb, while the amount of data requested by the post method is large and there is no limit.
3. Transmission speed: The transmission speed of get is higher than that of post
Because the usage method is the same, as long as the jQuery function is changed, the program can be switched between GET requests and POST requests
function getCookie(c_name){ if (document.cookie. length>0){ //First check whether the cookie is empty. If it is empty, return "" c_start=document.cookie.indexOf(c_name + "=") //Check whether the cookie exists through the indexOf() of the String object. If it does not exist, it is -1 if (c_start!=-1){ c_start=c_start + c_name.length+1 //The last +1 actually represents the "=" number, thus obtaining the starting position of the cookie value c_end= document.cookie.indexOf(";",c_start) //Actually, I was a little dizzy when I first saw the second parameter of indexOf(). Later I remembered that it means the specified starting index position...This sentence is to get the value end position. Because you need to consider whether it is the last item, you can judge whether the ";" sign exists if (c_end==-1) c_end=document.cookie.length return unescape(document.cookie.substring(c_start,c_end)) //The value is obtained through substring(). If you want to understand unescape(), you must first know what escape() does. It is a very important foundation. If you want to know more, you can search. The details of cookie encoding will also be explained at the end of the article} } return "" }
$.cookie("groupCode",222)
document.cookie = "name=value;expires=date"
document.cookie = "username=zhangsan ";document.cookie = "username=lisi";var cookies = document.cookie;console.log(cookies);
= "username=zhangsan";document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";var cookies = document.cookie;console.log(cookies);
for is the most commonly used loop, mainly used to loop arrays
let arr = [1,2,3];for (let i=0; i<arr.length; i++){ console.log(i,arr[i])}// 0 1// 1 2// 2 3
Syntax: arr.forEach(callback(currentValue [, index [, array]])[, thisArg]);
callback is a function executed for each element in the array. The function receives three parameters, currentValue (the current element being processed in the array), index (the index of the current element being processed in the array), array (The array that the forEach() method is operating on)
thisArg is the value used as this when the callback function callback is executed.
let arr = [1, 2, , 3]let arrCopy1 = []arr.map((item, index, arr) => { arrCopy1.push(item * 2)})console.log(arrCopy1)// [2, 4, 6]
forEach() executes the callback function once for each array element. Deleted or uninitialized items will be skipped ( e.g. on sparse arrays)
Unlike map() and reduce(), it has no return value and always returns undefind.
ForEach() has no way to abort or break out of the forEach() loop other than throwing an exception.
The while statement can loop to execute a specified piece of code under the premise that a certain conditional expression is true, until the loop ends when that expression is not true.
Example:
let n = 0; while (n < 3) { n++;}console.log(n);//expected output: 3Note
: Use the break statement to stop the loop before the condition evaluation result is true.
The do…while statement creates a loop that executes the specified statement until condition value is false. Detect condition after executing statement, so the specified statement is executed at least once
Example:
const list = ['a', 'b', 'c']let i = 0do { console.log(list[i]) //value console.log(i) //index i = i + 1} while (i < list.length)
The for…in loop can be used to traverse the enumerable attribute list of the object (including the [[Prototype]] chain) and
is mainly used to traverse the object. , the attribute value can be obtained through the attribute list
for (let property in object) { console.log(property) //property name console.log(object[property]) //property value}
Related recommendations: JavaScript learning tutorial
The above is a detailed summary of JavaScript learning knowledge points. For more information, please pay attention to other related articles on the PHP Chinese website!