关联数组SCSS/SASS

Dan*_*iel 33 arrays sass

我需要将数字转换为单词,所以:

  • "1-3" - >"三分之一"
  • "3-3" - >"三分之三"
  • "2-5" - >"五分之二"

这些数字是在一个循环中产生的,它应输出一群不同的类名等的one-thirdone-half:

$number = 3;

@for $i from 1 through $number-1 {
    // some calculations to output those classes: ".one-third", ".two-thirds"

    // The following currently outputs class names like ".1-3" and ".2-3"
    .#{$i}-#{$number} {
        // CSS styles
    }
}
Run Code Online (Sandbox Code Playgroud)

我想我需要使用两个不同的关联数组,在PHP中(仅作为示例)可能看起来像:

$1 = array( 
   "1"=>"one", 
   "2"=>"two", 
   "3"=>"three" 
);

$2 = array( 
   "1"=>"whole", 
   "2"=>"half", 
   "3"=>"third" 
);
Run Code Online (Sandbox Code Playgroud)

是否可以在SASS/SCSS中创建关联数组或是否有任何解决方法?

Mar*_*jak 56

在Sass <3.3中,您可以使用多维列表:

$numbers: (3 "three") (4 "four");

@each $i in $numbers {
    .#{nth($i,2)}-#{nth($i,1)} {
        /* CSS styles */
    }
}
Run Code Online (Sandbox Code Playgroud)

DEMO

在Sass> = 3.3中,我们得到了地图:

$numbers: ("3": "three", "4": "four");

@each $number, $i in $numbers {
    .#{$i}-#{$number} {
        /* CSS styles */
    }
}
Run Code Online (Sandbox Code Playgroud)

DEMO


因此,就分数而言,您可以在这个方向上做一些事情,这样您就不需要多个列表或地图:

$number: 6;
$name: (
    ("one"),
    ("two" "halv" "halves"),
    ("three" "third" "thirds"),
    ("four" "quarter" "quarters"),
    ("five" "fifth" "fifths"),
    ("six" "sixth" "sixsths")
);
Run Code Online (Sandbox Code Playgroud)

然后你想用你的循环做什么......甚至可能是这样的东西= D.

@for $i from 1 to $number {
  @for $j from 2 through $number {
    .#{ nth( nth( $name, $i ), 1 ) }-#{
      if( $i>1,
        nth( nth( $name, $j ), 3 ),
        nth( nth( $name, $j ), 2 )
      )} {
        /* CSS styles */
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

DEMO

(我是这样写的,所以你可以注意到@for,使用to去了n - 1)


小智 8

除了 Martin 的回答之外,我使用颜色作为变量的示例也适用于颜色处理函数,例如darken()

$blue: rgb(50, 57, 178);
$green: rgb(209, 229, 100);
$orange: rgb(255, 189, 29);
$purple: rgb(144, 19, 254);

$colors: (
        "blue": $blue,
        "green": $green,
        "orange": $orange,
        "purple": $purple
);

@each $name, $color in $colors {
  .tc-#{$name} { color: #{$color} !important; }
  .bgc-#{$name} { background-color: #{$color} !important; }
}
Run Code Online (Sandbox Code Playgroud)