preface
This is one of my series of articles about the basics of JavaScript. It does not talk about the efficiency of various types of loops, but mainly summarizes how to use them and understand some matters for attention. Click the title of the second and third levels to open the corresponding DOCUMENT of MDN.
If the article is helpful to you, please click on the like comment favorites and forward. If you have any questions or doubts, please leave a message in the comment section, and I will reply to you as soon as possible. If you think there is any knowledge point wrong in my article, PLEASE kindly inform me. It is fatal to understand the wrong things in pairs, no matter what industry you are in.
JavaScript in the loop
for
for... of
for... in
for await... of
forEach
This doesn’t really fit into this categorywhile
do... while
Create the basic data first, which is universal throughout the text.
const string='12345'
const array = [1.2.3.4.5]
const uint8Array=new Uint8Array([0.1.2.3])
const searchParams = new URLSearchParams("key1=value1&key2=value2");
const obj = {
'obj0': 1.'obj1': 2.'obj2': 3.'obj3': 4.'obj4': 5
}
const obj2 = Object.defineProperties({
'obj0': 1
}, {
'obj1': {
value: 2.enumerable: true
},
'obj2': {
value: 3.enumerable: true
},
'obj3': {
value: 4.enumerable: false}}); obj2.__proto__.obj4=5
const map = new Map([[0.1], [1.2], [2.3], [3.4], [4.5]])
const set = new Set([1.2.3.4.5])
Copy the code
for
Pure for is the most basic loop statement in JavaScript
for (let i = 0; i < array.length; i++) {
console.log(map.get(i)); // loop output 1, 2, 3, 4, 5
}
Copy the code
Let I = 0; let I = 0; i < array.length; I++, but, although the expression is optional, there are three; It’s mandatory.
for (let i = 0,j=0; ; i++,j++) {
// If you don't give him a break here, he will be gg
if (i > array.length) break;
console.log(i,j);
}
/ / 0 0
/ / 1 1
2 / / 2
/ / 3. 3
/ / 4 4
/ / 5 5
Copy the code
You can even declare a no-statement for loop if you need to, which is fine.
let j=[]
for (let i = 0; i < array.length; i++,j.push(i)); // The semicolon cannot be omitted
console.log(j) //[1, 2, 3, 4, 5]
Copy the code
for… of
for… The of statement loops over iterable objects (Array, Map, Set, String, TypedArray, arguments, etc.), the value of the object that is iterated over.
for (const element of array) {
console.log(element);// loop output 1, 2, 3, 4, 5
}
Copy the code
Note that ordinary objects are not iterable and cannot be used for… Of,
for (let element of obj) {
console.log(element); // TypeError: obj is not iterable
}
Copy the code
You can even loop strings
for (let element of string) {
console.log(element); // loop output 1, 2, 3, 4, 5
}
Copy the code
You can also loop Map and Set
for (let element of map) {
// This is an array
console.log(element[0],element[1]);
/ / 0 to 1
/ / 1. 2
/ / 2, 3
/ / 3 4
/ / 4 5
}
for (let element of set) {
console.log(element); // loop output 1, 2, 3, 4, 5
}
Copy the code
For the for… A loop of can be terminated by break, throw, continue, or return.
for (let element of set) {
if(element>3) break
console.log(element); // loop output 1, 2, 3
}
Copy the code
For ordinary objects that are not supported, we can create an iterator for them, which also implements for… Of circulation.
obj[Symbol.iterator] = function* (){
var keys = Object.keys(obj);
for(var key of keys){
yield [key,obj[key]]
}
};
for(var [key,value] of obj){
console.log(key,value);
// obj0 1
// obj1 2
// obj2 3
// obj3 4
// obj4 5
}
Copy the code
Traversal can also be achieved with object.entries (), which returns an array of key-value pairs for a given Object’s own enumerable properties.
for (const [key, value] of Object.entries(obj2)) {
console.log(`${key}: ${value}`);
//obj0: 1
//obj1: 2
//obj2: 3
}
Copy the code
There are other iterables that can use for… Of, I’m not going to give you one example.
for… in
for… The in statement iterates through the enumerable properties of an object other than Symbol in any order, including inherited enumerable properties. Note that the statement does not guarantee the order in which the properties are iterated.
for (let prop in obj) {
console.log(prop + "=" + obj[prop]);
// obj0 = 1
// obj1 = 2
// obj2 = 3
// obj3 = 4
// obj4 = 5
}
Copy the code
Obj2 [‘obj4’] is an inherited attribute (__proto__). Obj2 [‘obj4’] is an inherited attribute (__proto__). Obj2 [‘obj4’] is an inherited attribute (__proto__).
for (let prop in obj2) {
console.log(prop + "=" + obj2[prop]);
// obj0 = 1
// obj1 = 2
// obj2 = 3
// obj4 = 5
}
Copy the code
If you only need its own property, you can use hasOwnProperty to determine
for (let prop in obj2) {
if (obj2.hasOwnProperty(prop)) {
console.log(prop + "=" + obj[prop]);
}
// obj0 = 1
// obj1 = 2
// obj2 = 3
}
Copy the code
for await… of
And for… Fo is the same, but it only works with asynchronous iterators that are asynchronously iterable.
function getRes(){
return fetch('http://whois.pconline.com.cn/ip.jsp')
.then(response= > 'res')}async function test(){
let i=0
let arr = [getRes(),getRes(),getRes()]
for await (let x of arr){
i++
console.log(x+The '-'+i); // Loop out res-- 1 res-- 2 res-- 3
}
}
test()
Copy the code
Asynchronous generators already implement the asynchronous iterator protocol, so you can use for await… Of circulation.
async function* asyncGenerator() {
let i = 0;
while (i < 3) {
yieldi++; }}async function test(){
for await (num of asyncGenerator()) {
if (num>1) break; // You can also use break to abort, completely and for... Of the same
console.log(num); // Loop 0, 0 in order
}
}
test()
Copy the code
while
A while statement executes a specified piece of code as long as a conditional expression is true, and ends the loop if that expression is not true.
let n=0
while (n < array.length) {
console.log(array[n]); // loop output 1, 2, 3, 4, 5
n++;
}
Copy the code
do… while
do… The while statement creates a loop that executes the specified statement until the condition value is false. The condition in the while is detected after the code in post-DO is executed, so the code in DO is executed at least once.
let n=0
do {
console.log(array[n]); // loop output 1, 2, 3, 4, 5
n++;
}while (n < array.length)
do {
console.log(array[n]); //1 will loop at least once
n++;
}while (n < 0)
Copy the code
forEach
Array, Map, Set, NodeList, TypedArray, URLSearchParams all have forEach methods that execute a given function once on each element of the above type, returning no value. All except URLSearchParams have a second thisArg optional parameter, as shown in map.prototype. forEach.
Map.prototype.forEach
map.forEach((value,key,myMap) = >{
console.log(`${key}-${value}-${myMap.get(key)}`)
/ / 0-1-1
/ / 1-2-2
/ / 2-3-3
/ / 3-4-4
/ / 4-5-5
})
// The second argument is no longer an example of the following types in this article. Arrow functions cannot be used here
ThisArg is ignored if you pass in the function argument using an arrow function expression, because the arrow function is lexically bound to this.
map.forEach(function(value,key,myMap){
console.log(`${key}-${value}-${myMap.get(key)}-The ${this.exp}`)
// 0-1-1-exp
// 1-2-2-exp
// 2-3-3-exp
// 3-4-4-exp
// 4-5-5-exp}, {exp:'exp'})
Copy the code
Array.prototype.forEach
forEach
Method executes, in ascending order, for each entry in the array that has a valid valuecallback
Functions;forEach
Does not change the original array, but can be modified by callback;forEach
Non-chain call;forEach
The traversal scope is called the first timecallback
Will determine before;- There is no way to abort or jump out except by throwing an exception
forEach
Cycle; - If an existing value is changed,
callback
You get the latest value; - call
forEach
Items added later to the array will not becallback
To access; - Deleted items are not traversed. If the accessed element is deleted during the iteration (e.g
shift
), subsequent elements will be skipped.
array.forEach((currentValue, index ,myArray) = > {
console.log(`${currentValue}-${index}-${myArray[index]}`);
/ / 1-0-1
/ / 2-1-2
/ / 3-2-3
/ / 4-3-4
/ / 5-4-5
});
Copy the code
The scope of forEach traversal is determined before the first callback is called. Items added to the array after a call to forEach are not accessed by the callback. If an existing value is changed, the value passed to the callback is forEach(the value traversed up to their point in time). Deleted items are not traversed. If an already accessed element is removed during iteration (for example, with Shift), subsequent elements are skipped.
array.forEach((currentValue) = > {
if (currentValue === 1) {
// If an existing value is changed, the value passed to the callback is the value that forEach() traversed up to their moment
array[4] = Awesome!
// The scope of forEach traversal is determined before the first callback is called
array.push(777)}console.log(currentValue)
// 1 2 3 4 666
});
array.forEach((currentValue) = > {
if (currentValue === 1) {
array.shift();
}
// When I reach 1, currentValue is already 1, so I can print it out and delete the first one in the array, resulting in
// All arrays take a step forward [2,3,4,5], but at this point, the index is already 1, so skip 2 and print 3,4,5
console.log(currentValue)
/ / 1
/ / 3
/ / 4
/ / 5
});
Copy the code
There is no way to abort or break out of the forEach() loop except by throwing an exception
array.forEach((currentValue) = > {
if(currentValue>3) break; // Uncaught SyntaxError: Illegal break statement
console.log(currentValue)
});
Copy the code
Flat arrays can be seen in my article
Set.prototype.forEach
set.forEach((value,mySet) = >{
console.log(`${value}-${mySet}`)
/ / 1-1
/ / 2-2
/ / 3 to 3
/ / 4-4
/ / 5-5
})
Copy the code
NodeList.prototype.forEach
let node = document.createElement("div");
let kid1 = document.createElement("p");
let kid2 = document.createTextNode("hey");
let kid3 = document.createElement("span");
node.appendChild(kid1);
node.appendChild(kid2);
node.appendChild(kid3);
let list = node.childNodes;
list.forEach((currentValue, currentIndex, listObj) = > {
console.log(`${currentValue}-${currentIndex}-${listObj[currentIndex]}`)
// [object HTMLParagraphElement]-0-[object HTMLParagraphElement]
// [object Text]-1- [object Text]
// [object HTMLSpanElement]-2- [object HTMLSpanElement]});Copy the code
TypedArray.prototype.forEach
TypedArray a TypedArray
uint8Array.forEach((element, index, array) = >{
console.log(`${element}-${index}-${array[index]}`)
/ / 0 0 0
/ / 1-1-1
/ / 2-2-2
/ / 3-3-3
});
Copy the code
URLSearchParams.forEach
searchParams.forEach((value, key,searchParams) = > {
console.log(value, key,searchParams.get(key));
// value1 key1 value1
// value2 key2 value2
});
Copy the code
for… Of and the for… Similarities and differences in
- The same
for... in
andfor... of
Statements are loops (iterates) over something;- Can be
break,continue
andreturn
Interrupt traversal.
- The difference between
for... in
Statement traverses the division of an object in any orderSymbol
Outside of theEnumerable property.Including inheritanceNote: the statement does not guarantee traversal order;for... in
Iterating over the keys of the object, whilefor... of
The value corresponding to the key of the iterated object;for... in
You can iterate over any object, butfor... of
You need the object to beIterable;;
do… While and while have similarities and differences
Similarities: both loop statements Difference: do… While loops at least once
Break,continue, and return in JavaScript
return
The return statement terminates the function and returns a specified value to the caller, or undefined if ignored.
Array.foreach is a method inside f(). A return inside array.foreach is different from a return inside f().
// In the function
function f() {
array.forEach((item) = >{
console.log(item) // return invalid print 1, 2, 3, 4, 5 consecutively
return item+1 //array.forEach has no return value
})
console.log(2) / / print 2
}
console.log(f()) //undefined
// in the global scope
array.forEach((item) = >{
console.log(item)
return item+1 // return invalid print 1, 2, 3, 4, 5 consecutively
})
console.log(3) / / print 3
Copy the code
Use for inside a function or in a global scope. In, return can normally interrupt for… In statement execution
// In the function
function f() {
for (const objElement in array) {
console.log(array[objElement]) / / 1
return array[objElement]
}
console.log(2) // Unable to print, function execution aborted
}
console.log(f()) / / 1
// in the global scope
for (const objElement in array) {
console.log(array[objElement]) / / 1
return array[objElement]
}
console.log(3) // Unable to print, aborted
Copy the code
Use for inside a function or in a global scope. Of, return can normally interrupt for… Of statement execution
// In the function
function f() {
for (const objElement of array) {
console.log(objElement) / / 1
return objElement
}
console.log(2) // Unable to print, function execution aborted
}
console.log(f()) / / 1
// in the global scope
for (const objElement of array) {
console.log(objElement) / / 1
return objElement
}
console.log(3) // Unable to print, aborted
Copy the code
Using for inside a function or in a global scope, return interrupts the for statement normally
// In the function
function f() {
for (let i = 0; i < array.length; i++) {
console.log(array[i]) / / 1
return array[i]
}
console.log(2) // Unable to print, function execution aborted
}
console.log(f()) / / 1
// in the global scope
for (let i = 0; i < array.length; i++) {
console.log(array[i]) // The node environment is inconsistent with v8
return array[i]
}
console.log(3) // Unable to print, execution aborted
Copy the code
Use while and do inside functions or in global scopes. While, return can normally interrupt while and do… While statement execution
// In the function
function f() {
let n=0
while (n < array.length) {
n++;
if (n === 3) {
return 'f';
}
console.log(n) / / 1. 2
}
console.log(2) / / 2
}
console.log(f()) //f
// in the global scope
let n=0
while (n < array.length) {
n++;
if (n === 3) {
return 'f'; // Illegal return statement
}
console.log(n)
}
console.log(3)
Copy the code
Summary:
return
At this time will beThe statement in progress stops, butreturn
More suitable for function statements;- for
forEach
Method, which cannot be broken except by throwing an exception, is deprecated later in this sectionforEach
Give an example.
break
The break statement interrupts the current loop, switch, or label statement (see article below) and transfers program control to the statement immediately following the aborted statement.
Use for inside a function or in a global scope. In, break can normally interrupt the current loop, but does not prevent subsequent program execution.
// In the function
function f() {
for (const objElement in array) {
console.log(array[objElement]) / / 1
break
}
console.log(2) / / 2
}
//
console.log(f()) //undefined
// // is in global scope
for (const objElement in array) {
console.log(array[objElement]) / / 1
break
}
console.log(3) / / 3
Copy the code
Use for inside a function or in a global scope. Of, break can normally interrupt the current loop, but does not prevent subsequent program execution.
// In the function
function f() {
for (const objElement of array) {
console.log(objElement) / / 1
break
}
console.log(2) / / 2
}
//
console.log(f()) //undefined
// // is in global scope
for (const objElement of array) {
console.log(objElement) / / 1
break
}
console.log(3) / / 3
Copy the code
Using for inside a function or in a global scope, break normally interrupts the current loop but does not prevent subsequent program execution.
// In the function
function f() {
for (let i = 0; i < array.length; i++) {
console.log(array[i]) / / 1
break;
}
console.log(2) / / 2
}
//
console.log(f()) //undefined
// // is in global scope
for (let i = 0; i < array.length; i++) {
console.log(array[i]) / / 1
break;
}
console.log(3) / / 3
Copy the code
Use while and do inside functions or in global scopes. While, break normally interrupts the current loop but does not prevent subsequent program execution.
// In the function
function f() {
let n=0
while (n < array.length) {
n++;
if (n === 3) {
break;
}
console.log(n) / / 1. 2
}
console.log(2) / / 2
}
console.log(f()) //undefined
// in the global scope
let n=0
while (n < array.length) {
n++;
if (n === 3) {
break;
}
console.log(n) / / 1. 2
}
console.log(3) / / 3
Copy the code
Summary: break terminates the current loop, but does not prevent subsequent program execution;
continue
Continue Skips this loop and continues with the next loop.
// In the function
function f() {
for (let i = 0; i < array.length; i++) {
if(array[i] === 1) continue;
console.log(array[i]) // 2 3 4 5
}
console.log(2) / / 2
}
console.log(f()) //undefined
// in the global scope
for (let i = 0; i < array.length; i++) {
if(array[i] === 1) continue;
console.log(array[i]) // 2 3 4 5
}
console.log(3) / / 3
Copy the code
Use for inside a function or in a global scope. In, continue can normally skip this loop and continue the next loop.
// In the function
function f() {
for (const objElement in array) {
if(array[objElement] === 1) continue;
console.log(array[objElement]) // 2 3 4 5
}
console.log(2) / / 2
}
console.log(f()) //undefined
// in the global scope
for (const objElement in array) {
if(array[objElement] === 1) continue;
console.log(array[objElement]) // 2 3 4 5
}
console.log(3) / / 3
Copy the code
Use for inside a function or in a global scope. Of, continue Normally skips this loop and continues the next loop.
// In the function
function f() {
for (const objElement of array) {
if(objElement === 1) continue;
console.log(objElement) // 2 3 4 5
}
console.log(2) / / 2
}
console.log(f()) //undefined
// in the global scope
for (const objElement of array) {
if(objElement === 1) continue;
console.log(objElement) // 2 3 4 5
}
console.log(3) / / 3
Copy the code
Use while and do inside functions or in global scopes. While, continue skips this loop and continues the next loop.
// In the function
function f() {
let n=0
while (n < array.length) {
n++;
if (n === 3) {
continue;
}
console.log(n) // 1 2 4 5
}
console.log(2) / / 2
}
console.log(f()) //undefined
// in the global scope
let n=0
while (n < array.length) {
n++;
if (n === 3) {
continue;
}
console.log(n) // 1 2 4 5
}
console.log(3) / / 3
Copy the code
Summary: continue is used to skip this loop and continue the next loop.
conclusion
forEach
There is no break except to throw an exception;- All three stop/skip statements at this point;
break
Interrupts the current loop without preventing subsequent program execution;continue
Skip this loop and continue with the next loop;return
Is a function return statement, but the return also stops the function;- The statement environment used is different,
break
andcontinue
Is used to cycle orswitch
Statement,return
Is used in function statements.
reference
How do break,continue and return work in @is_tao MDN js?