1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
|
---
layout: default
permalink: docs/hashes.html
---
# Hashes
In `0.39.0` version Stylus got hash objects.
## Define
You can define a hash using the curly braces and colons to divide the keys and values:
foo = {
bar: baz,
baz: raz
}
the keys should be either proper idents or strings:
foo = {
bar: baz,
'baz': raz,
'0': raz
}
When you already have a hash, you can set its values using brackets and strings inside:
foo = {}
foo['bar'] = baz
foo['baz'] = raz
Note that while you can't use variables or interpolations in curly braces defines, you can use variables inside brackets:
foo = {}
bar = 'baz'
foo[bar] = raz
foo.baz
// => raz
## Getters
For retrieving values from hashes you can use the dot for idents:
foo = { bar: "baz" }
foo.bar
// => "baz"
Or brackets with strings for anything:
foo = { "%": 10 }
baz = "%"
foo[baz]
// => 10
You can use any combinations you want:
foo = {
bar: {
baz: {
raz: 10px
}
}
}
qux = "raz"
foo["bar"].baz[qux]
// => 10px
## Interpolation
Hashes used inside an interpolation would output the content of the hashes as CSS (without almost any Stylus features though):
foo = {
width: 10px,
height: 20px,
'&:hover': {
padding: 0
}
}
.bar
{foo}
// => .bar {
// width: 10px;
// height: 20px;
// }
// .bar:hover {
// padding: 0;
// }
## Other stuff
You can use other normal Stylus stuff with hashes, like `length()`:
foo = { bar: 'a', baz: 'b' }
length(foo)
// => 2
You can iterate through hashes with optional key param:
foo = { width: 10px, height: 20px }
for key, value in foo
{key}: value
// => width: 10px;
// height: 20px;
You can check existence of a key in hash using `in`:
foo = { bar: 10px}
bar in foo
// => true
baz in foo
// => false
You can get keys or values of the hash using corresponding bifs:
foo = { bar: 'a', baz: 'b' }
keys(foo)
// => 'bar' 'baz'
values(foo)
// => 'a' 'b'
And you can use `merge` (aliased as `extend`) to merge hashes:
obj = {
foo: 'foo'
bar: 'bar'
}
obj2 = {
baz: 'baz'
}
merge(obj, obj2)
// => {"foo":"('foo')","bar":"('bar')","baz":"('baz')"}
|