Less循环中Guard的使用及减少循环次数优化样式输出问题
Hey there! Let's break down your two Less questions step by step.
Guard clauses in Less are conditional checks that control when a mixin (or loop iteration) runs—and you’re already using one effectively in your code!
Take your existing loop definition:
.loop (@n, @j: @n) when (@j >= 0) { // Loop logic here }
The when (@j >= 0) part is the guard. It tells Less to only execute this .loop mixin if @j is greater than or equal to 0. This acts as your loop’s stop condition: once @j drops below 0, the guard fails, and the recursion stops.
You can also combine multiple conditions with and or or for more granular control. For example, if you wanted to only run iterations for even values of @j that are also >= 0, you’d write:
.loop (@n, @j: @n) when (@j >= 0) and (@j % 2 = 0) { // Logic for even values only }
Absolutely! We can not only cut down on unnecessary iterations but also fix the class names to remove that trailing -0 for integer values. Here’s the optimized code:
.loop(2); .loop(@n, @j: @n) when (@j >= 0) { // Calculate integer and fractional parts @i: floor(@j); @f: floor(mod(@j, 1)*10); // Generate clean class names: no "-0" for integers & when (@f = 0) { .height-@{i} { height: 1% * @j; } } & when (@f > 0) { .height-@{i}-@{f} { height: 1% * @j; } } // Recurse with decremented value (stops when @j < 0) .loop(@n, @j - 0.5); }
Key improvements:
- Fixed iteration order: We generate the styles before making the recursive call. Your original code recursed first, which meant it skipped processing
@j=2and@j=1.5—now we capture all values from 2 down to 0. - Conditional class names: Nested guards (
& when (@f = 0)) check if the fractional part is 0, and output a simpler class name for integers (like.height-0instead of.height-0-0). - Leaner loop: The guard
when (@j >= 0)still handles termination, but we’re no longer generating redundant class names with-0suffixes, which eliminates unnecessary work.
Expected output:
.height-2 { height: 2%; } .height-1-5 { height: 1.5%; } .height-1 { height: 1%; } .height-0-5 { height: 0.5%; } .height-0 { height: 0%; }
If you prefer the output ordered from smallest to largest (0 → 2), just move the recursive call line above the class generation logic. That way, it processes 0 first, then 0.5, and so on up to 2.
内容的提问来源于stack exchange,提问作者Goffer

