Usually we are most familiar with the For loop.
For example, the size of a set of numbers, you can use the bubbling method.
var a=[];
for (var d=0;d<5;d++) {
var b= Window.prompt ("Please enter Number:");
a[d]=parseint (b);
}
for (var n=0;n<a.length;n++) {
for (Var i=0;i<a.length-n;i++) {
if (A[i]>a[i+1]) {
var temp=a[i+1];
a[i+1]=a[i];
a[i]=temp;
}
}
}
document.write (a);
The current JS new feature, foreach, iterates through each element, providing us with the convenience.
foreach is generally used for looping arrays, and for in is generally used for looping objects.
The foreach statement does not completely replace the For statement, however, any foreach statement can be rewritten as a version of the for statement.
Let's look at an example that uses foreach to iterate through each element and multiply it by 10.
var a=[9,8,7,10,5,4,3];
var b=[];
A.foreach (function (value,i) {
b[i]=a[i]*10;
});
Console.log (a);
Console.log (b);
The above mentioned for...in, generally used to traverse the object, you can look at the following example:
var obj={
Name: "Zhang Fei",
AGE:20,
Gender: "Male"
};
Console.log (obj);
For (var k in obj) {
Console.log ([k,obj[k]]);
}
For arrays, there is a map method that not only loops the function, but also returns the value to the new array as a callback function.
var a=[9,8,7,10,5,12,3];
var myary= a.map (function (value) {
return value*10; //If you do not write return, the new array will have the length of the original array, but the value inside is undefined
if (value>10) {
return value*10;
}else{ //need to write else, otherwise less than 10 is undefined
return value;
}
});
console.log (myary);
filter, filters the array, the condition of the return, and map is different from the non-conforming does not return, also does not appear undefined.
var myary1= a.filter (function (value) {
if (value>10) {
return value;
}
});
Console.log (MyAry1);
Some uses of for, foreach, filter, and so on