Since I've been working in VB and Delphi, I'm always a little confused about how to specify the loop value when writing a C / C ++ for statement such as JavaScript, so make a note of it.
The simple way to write when you want the index value to loop from 0 to length -1 is as follows.
i ++ and i-- respect JsLint and try not to use it.
var str = 'abc';
for (var i = 0; i <= str.length - 1; i += 1) {
console.log(str[i]);
}
//Output in order of a b c
However, I think that it is a language characteristic of the C-type for statement, but the end judgment part of the for loop for each loop
i <= str.length - 1
Because this is evaluated, the process of getting str.length occurs every time, which makes the loop a little slower.
Therefore, it is better to assign the number of loops to a variable first with an emphasis on speeding up.
```javascript
var str = 'abc';
for (var i = 0, il = str.length - 1; i <= il; i += 1) {
console.log(str[i]);
}
//Output in order of a b c
This is also written like this.
var str = 'abc';
for (var i = 0, il = str.length; i < il; i += 1) {
console.log(str[i]);
}
//Output in order of a b c
This makes it hard to read the end value of the loop, which still makes me feel a little uncomfortable, but for C / C ++ / Java people, it's not unreadable, so it's a common code. It would be nice to be able to read it.
In the reverse order, it is better to write like this.
var str = 'abc';
for (var i = str.length - 1; 0 <= i; i -= 1) {
console.log(str[i]);
}
//Output in order of c b a
Also, if you devise and use the for syntax, you can also do the following.
for (var i = str.length; i--;) {
console.log(str[i]);
}
//Output in order of c b a
The full text of the operation check is as follows.
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title></title>
<script>
var str = 'abc';
for (var i = 0; i <= str.length - 1; i += 1) {
console.log(str[i]);
}
//Output in order of a b c
for (var i = 0, il = str.length - 1; i <= il; i += 1) {
console.log(str[i]);
}
//Output in order of a b c
for (var i = 0, il = str.length; i < il; i += 1) {
console.log(str[i]);
}
//Output in order of a b c
for (var i = str.length - 1; 0 <= i; i -= 1) {
console.log(str[i]);
}
//Output in order of c b a
for (var i = str.length; i--;) {
console.log(str[i]);
}
//Output in order of c b a
</script>
</head><body>
</body></html>
Recommended Posts