如何将Sass Map的键提取为整数变量?汉堡菜单工具类开发疑问
Hey there! Let's fix that Sass loop issue you're having with your hamburger menu helper classes. The problem sounds like you're not correctly extracting the integer keys (2 and 3) from your Sass Map—instead, you're getting the entire key-value pair or list assigned to $px. Here's how to resolve this and get your loops generating the right styles:
First, Define Your Maps/Lists Clearly
Let's start with a clean setup for your line sizes and spacings:
// Map storing line sizes: key = integer (2/3), value = pixel value $burger-line-sizes: ( 2: 2px, 3: 3px ); // List of spacing values between burger lines $burger-spacings: 4px, 6px, 8px;
Correctly Traverse the Map to Get Integer Keys
There are two straightforward ways to grab those integer keys:
Option 1: Traverse Key-Value Pairs Directly
Use Sass's @each syntax to separate the key and value from your Map. This gives you direct access to the integer key (like 2 or 3) and its corresponding pixel value:
@each $line-size-key, $line-size in $burger-line-sizes { // Loop through each spacing value @each $spacing in $burger-spacings { // Calculate total height of the hamburger icon (3 lines + 2 gaps) $total-icon-height: (3 * $line-size) + (2 * $spacing); // Generate a helper class using the integer key .hamburger--size-#{$line-size-key}px-spacing-#{$spacing} { height: $total-icon-height; .hamburger__line { height: $line-size; margin-bottom: $spacing; // Remove margin from the last line to avoid extra space &:last-child { margin-bottom: 0; } } } } }
Option 2: Extract Keys First with map-keys()
If you only need the integer keys (and not the pixel values right away), use map-keys() to get a list of just the keys, then loop through that list:
@each $line-size-key in map-keys($burger-line-sizes) { // Fetch the corresponding pixel value from the Map $line-size: map-get($burger-line-sizes, $line-size-key); // Rest of the spacing loop is identical to Option 1 @each $spacing in $burger-spacings { $total-icon-height: (3 * $line-size) + (2 * $spacing); .hamburger--size-#{$line-size-key}px-spacing-#{$spacing} { height: $total-icon-height; .hamburger__line { height: $line-size; margin-bottom: $spacing; &:last-child { margin-bottom: 0; } } } } }
Why Your Previous Code Wasn't Working
Chances are your original loop looked something like this:
// ❌ This assigns entire key-value tuples to $px, e.g., (2, 2px) @each $px in $burger-line-sizes { // ... your code }
Instead of getting just the integer key, $px was holding the full key-value pair (a Sass "tuple"). By explicitly separating the key and value in the @each statement, or using map-keys() to extract just the keys, you'll get the integer values (2 and 3) you need for your class names and calculations.
This setup will generate all combinations of line sizes and spacings, with accurate math for the hamburger icon's total height and line positioning.
内容的提问来源于stack exchange,提问作者havardlj

