Repeat process (loop processing)
Here, we will explain how to implement loop processing using an office script in conjunction with a sample code.
for statement
The description method that is often introduced as a sample of loop processing and obtaining the N's N's N's while counts up variables is often replaced with another description method in Office script.
Therefore, I will explain from the simplest and most highly readability for ... of
.
Loop processing using for-of statement
Use the for ... of
sentence when implementing the processing of each element that can be repeated.
Each element in the array can be received as a variable.
const fruits = ['Apple', 'Orange', 'Banana'];
// Repeated process for each element
for (const one of fruits) {
console.log(one);
}
Apple
Orange
Banana
Loop processing using for-in statement
Next is the loop process using for...in
sentence.
Unlike for...of
, you receive the index as a variable, not the element.
const sports = ['Football', 'Baseball', 'Basketball'];
// Repeated processing using an index
for (const i in sports) {
console.log(sports[i]);
}
Football
Baseball
Basketball
Loop processing using normal for statement
Finally, it is a loop process using normal for
sentence, which is often used in other languages.
const fruits = ['Apple', 'Orange', 'Banana'];
// Repeated processing using the length of the array
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Apple
Orange
Banana
continue and break
If you want to forcibly move to the next loop while processing the for
sentence, use continue
.
Also, if you interrupt the for
loop, use break
.
const sports = ['Baseball', 'Football', 'Basketball', 'TableTennis', 'Volleyball'];
for (let i = 0; i < sports.length; i++) {
if (i < 2) {
console.log('skipped');
continue;
}
if (i > 3) {
break;
}
console.log(sports[i]);
}
skipped
skipped
Basketball
TableTennis
forEach Method
An object that can be repeated in the Office script has the forEach
method.
You can use forEach
to perform processing for each element.
const fruits = ['Apple', 'Orange', 'Banana'];
// Repeated process for each element
fruits.forEach((fruit, i) => {
console.log(`The ${i + 1}th fruit is ${fruit}`);
});
The 1th fruit is Apple
The 2th fruit is Orange
The 3th fruit is Banana
The second argument of the callback function can be omitted.
while statement
while
Explains how to implement loop processing using sentences.
The for
sentence is often used for repetitive variables, whereas the while statement is suitable for loop processing until certain conditions are met.
let count = 0;
while (count < 1000) {
count++;
}
console.log(count);
1000