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
Section titled “for statement”Loop processing using for-of statement
Section titled “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 elementfor (const one of fruits) { console.log(one);}AppleOrangeBananaLoop processing using for-in statement
Section titled “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 indexfor (const i in sports) { console.log(sports[i]);}FootballBaseballBasketballLoop processing using normal for statement
Section titled “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 arrayfor (let i = 0; i < fruits.length; i++) { console.log(fruits[i]);}AppleOrangeBananacontinue and break
Section titled “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]);}skippedskippedBasketballTableTennisforEach Method
Section titled “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 elementfruits.forEach((fruit, i) => { console.log(`The ${i + 1}th fruit is ${fruit}`);});The 1th fruit is AppleThe 2th fruit is OrangeThe 3th fruit is BananaThe second argument of the callback function can be omitted.
while statement
Section titled “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