Home > Web Front-end > JS Tutorial > body text

Advanced for loop writing method

一个新手
Release: 2017-09-23 10:04:11
Original
1746 people have browsed it

1. Commonly used writing methods:

for(var i=0;i<arr.length;i++){
console.log(i);
console.log(arr[i]);
}
Copy after login

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]);
}
Copy after login

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);
}
Copy after login

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];
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!