JS and for .. in. And for of the difference between

The basic format for general circulation as follows:

for(int i ; i < 10 ; i++){
    ...
}

Also for loop format exists in the js. For ..in and for ... of, the following will explain the difference between these two

is a standard for in ES5, traversing Key. 
for ES6 is of the standard traversal value.

 

... in for   : traversing a property of an object, similar to the key-value pairs in the key key, when it is traversing the array traversal of the array index ,

var a = ['A', 'B', 'C'];
for (var i in a) {
 alert(i); // '0', '1', '2'
 alert(a[i]); // 'A', 'B', 'C'
}

for ... of:   cycling is the new syntax introduced ES6 (but there are a lot browser does not support or even error,)

For ... of a loop through the collection , use the following:

var a = ['A', 'B', 'C'];
var s = new Set(['A', 'B', 'C']);
var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
for (var x of a) { // 遍历Array
 alert(x);//'A', 'B', 'C'
}
for (var x of s) { // 遍历Set
 alert(x);//'A', 'B', 'C'
}
for (var x of m) { // 遍历Map
 alert(x[0] + '=' + x[1]);//1='x',2='y',3='z'
}

When using two cycles to parse json data:

//for in 循环
for(var d in data){
	html+="<tr><td>"+ data[d].id + " </td> <td>"+ data[d].name +" </td> <td>" 
             + data[d].password+"</td> </tr>";
}

//for of 循环
for(var d of data){
	html+="<tr><td>"+ d['id'] + " </td> <td>"+ d['name'] +" </td> <td>" + d['password']
               +" </td> </tr>"
}

 

Guess you like

Origin blog.csdn.net/qq_34851243/article/details/90967828