Application and difference between for and with for

for and applications with for
1.
Commonly used for: traverse arrays and objects
for (statement 1; statement 2; statement 3)
{ code block to be executed } statement 1 (code block) executed before statement 2 defines the run loop (code block) ) Condition Statement 3 is executed after the loop (code block) has been executed




实例
	sum = 0;
    for (var i = 0; i < 5; i++) {
    
    
      sum += i;
    }
    console.log(sum);//10
   

Double for loop
// Print five rows and five columns of stars
var str ='';
for (var i = 1; i <= 5; i++) {//The outer loop is responsible for printing five lines
for (var j = 1; j <= 5 ; j++) { str = str +'★' } // If a line is printed with 5 stars, a new line must be added\n str = str +'\n'; } console.log(str);






Insert picture description here

2. The foreach
forEach() method executes the provided function once for each element of the array.

iterable.forEach(function(value, key, iterable) {
    
    
  console.log(key, value, iterable);
});
实例:
var array = ['a', 'b', 'c'];

array.forEach(function(element) {
    
    
  console.log(element);//a,b,c
});

The function callback in the forEach method has three parameters: the
first parameter is the content of the traversed array, the
second parameter is the corresponding array index, and the
third parameter is the array itself
var arr = [1,2,3,4];

var sum =0;
arr.forEach(function(value,index,array){
    
    

 array[index] == value; //结果为true

 sum+=value; 

 });

console.log(sum); //结果为 10

Three, for in
for ... in statement is used to traverse the array or the properties of the object (or an object property array for circulating operation).

arr = [1, 2, 3, 4, 5, 65, 7, 8, 9, 6];
    for (let k in arr) {
    
    
      console.log(k);
      console.log(arr[k])
    }
    0
    1
    1
    2
    2
    3
    3
    。。。
    

You can traverse both the index value and the value

四、for of

arr = [1, 2, 3, 4, 5, 65, 7, 8, 9, 6];
    for (let k of arr) {
    
    
      console.log(k);
      console.log(arr[k]);
    }
    1
    1
    2
    2
    3
    3
    。。。

Can only traverse value, not index

The difference between for in and for of
1. Traverse objects usually use for in to traverse the key name of the object.
2. For in traverses the index (key name) of the array, while for of traverses the value of the array element.

Guess you like

Origin blog.csdn.net/qq_36291960/article/details/108912429