Loop statement specification
Loop statements are essential tools for controlling flow in JavaScript, and proper conventions can enhance code readability and maintainability. Below are common loop statement conventions and practical recommendations.
Choosing Basic Loop Types
Prefer for
loops for scenarios with a known number of iterations, while
loops for uncertain conditions, and for...of
for iterable object traversal. Avoid using for...in
to traverse arrays unless handling special cases like sparse arrays.
// Recommended - Array traversal
const arr = [1, 2, 3];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// Recommended - Iterable objects
const set = new Set([1, 2, 3]);
for (const item of set) {
console.log(item);
}
Loop Control Variables
Loop counters should be declared with let
to avoid polluting the outer scope. Counter names should be descriptive, with single-letter variables reserved for simple loops.
// Not recommended
for (var i = 0; i < 10; i++) { /*...*/ }
// Recommended
for (let index = 0; index < users.length; index++) {
const user = users[index];
// ...
}
Controlling Loop Body Complexity
A single loop body should not exceed 20 lines of code. Complex logic should be extracted into standalone functions. Refactor if nested loops exceed two levels.
// Not recommended
for (const item of list) {
// 50 lines of business logic...
}
// Recommended
function processItem(item) {
// Encapsulate complex logic
}
for (const item of list) {
processItem(item);
}
Early Termination and Skipping
Use break
and continue
judiciously, adding comments to explain conditions. return
can terminate the entire function containing the loop.
for (const user of users) {
if (user.inactive) continue; // Skip inactive users
if (user.role === 'admin') {
foundAdmin = user;
break; // Terminate after finding the first admin
}
}
Performance Optimization Tips
Pay special attention to performance-critical points like caching array lengths, avoiding repeated calculations within loops, and minimizing DOM operations.
// Before optimization
for (let i = 0; i < document.getElementsByTagName('div').length; i++) {
// Recalculates length every iteration
}
// After optimization
const divs = document.getElementsByTagName('div');
for (let i = 0, len = divs.length; i < len; i++) {
// Cached length
}
Handling Asynchronous Loops
Use for...of
with await
for asynchronous loops, avoiding pitfalls with forEach
and async operations.
// Not recommended
items.forEach(async (item) => {
await process(item); // Will not wait as expected
});
// Recommended
for (const item of items) {
await process(item); // Executes sequentially
}
Immutability Principle
Modifying an array while iterating over it can lead to unexpected behavior. Create a copy if special handling is required.
const numbers = [1, 2, 3, 4];
// Risky operation
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
numbers.splice(i, 1); // Mutates the original array
i--; // Manual index adjustment required
}
}
// Safer approach
const filtered = numbers.filter(n => n % 2 !== 0);
Loops vs. Functional Programming
In modern JavaScript, many loop scenarios can be replaced with functional methods like map
, filter
, or reduce
, but be mindful of performance differences.
// Traditional loop
let sum = 0;
for (const num of numbers) {
sum += num;
}
// Functional approach
const sum = numbers.reduce((acc, num) => acc + num, 0);
Error Handling Patterns
Wrap specific operations inside loops with try-catch
to avoid interrupting the entire loop due to a single failure.
for (const task of tasks) {
try {
await executeTask(task);
} catch (error) {
console.error(`Task ${task.id} failed:`, error);
continue; // Proceed with subsequent tasks
}
}
Loop Variable Scope
Loop variables declared with let
have block scope, while var
causes hoisting and shared variable issues.
// Problematic example
var funcs = [];
for (var i = 0; i < 3; i++) {
funcs.push(() => console.log(i)); // All output 3
}
// Correct approach
const funcs = [];
for (let i = 0; i < 3; i++) {
funcs.push(() => console.log(i)); // Outputs 0, 1, 2
}
Loops and Generators
Complex loop logic can be encapsulated in generator functions for lazy evaluation and clearer control flow.
function* paginate(items, pageSize) {
for (let i = 0; i < items.length; i += pageSize) {
yield items.slice(i, i + pageSize);
}
}
for (const page of paginate(allItems, 10)) {
// Process 10 items at a time
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:条件语句规范