Home > Article > Web Front-end > Advanced for loop writing method
1. Commonly used writing methods:
for(var i=0;i<arr.length;i++){ console.log(i); console.log(arr[i]); }
You need to read arr.length once every time to make a judgment
2,
for(var i=0,len=arr.length;i<len;i++){ console.log(i); console.log(arr[i]); }
The variables are completely defined, there is no need to retrieve the length from the array, and the computer can directly determine i and length
3,
for(var i=0,val;val=arr[i++];){ console.log(i); console.log(val); }
Put judgment and assignment together, and assign values while looping;
Look at another for(var i=10;i--;){console.log(i);}
At first glance, you may think it is wrong because the statement is not complete, but the loop will be 10 times. Why?
Because the second sentence of the conditional sentence ib769563f2f8915213facfc87dd415c3carr.length, then val is undefined, the judgment is undefined, the judgment is terminated, and the loop ends;
Therefore, the loop You can use abbreviations such as 0, null, undefined, false and empty strings to make judgments and learn programming thinking.
The above is the detailed content of Advanced for loop writing method. For more information, please follow other related articles on the PHP Chinese website!