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 i<10; returns true; and in js, 0, null, undefined, false and empty string will all be false values
So, in i When it becomes 0, it is automatically converted to a Boolean value false, thereby ending the loop;
If you understand this, then look back at the third way of writing above,
for(var i = 0;i<arr.length;i++){ var val = arr[i]; }
i = 0 and var at the same time Put in the initial condition, val = arr[i++] is judged. If arr[i++]>arr.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!