Clojure 如何获取试剂中项目的索引

Clojure 如何获取试剂中项目的索引,clojure,clojurescript,reagent,hiccup,Clojure,Clojurescript,Reagent,Hiccup,当我在试剂中迭代向量时,如下所示: (for [item ["rattata" "pidgey" "spearow"]] [:li item])]) [:li item index] (defmacro for-indexed [[item coll] & body] `(for [i# (range (count ~coll))] (let [~item [i# (nth ~coll i#)]] ~@body))) (for-indexed

当我在试剂中迭代向量时,如下所示:

(for [item ["rattata" "pidgey" "spearow"]]
  [:li item])])
  [:li item index]
(defmacro for-indexed [[item coll] & body]
  `(for [i# (range (count ~coll))] 
     (let [~item [i# (nth ~coll i#)]]
       ~@body)))

(for-indexed [item ["rattata" "pidgey" "spearow"]]
  [:li item])

;; => ([:li [0 "rattata"]] [:li [1 "pidgey"]] [:li [2 "spearow"]])
我想获得一个特定项目的索引-如下所示:

(for [item ["rattata" "pidgey" "spearow"]]
  [:li item])])
  [:li item index]
(defmacro for-indexed [[item coll] & body]
  `(for [i# (range (count ~coll))] 
     (let [~item [i# (nth ~coll i#)]]
       ~@body)))

(for-indexed [item ["rattata" "pidgey" "spearow"]]
  [:li item])

;; => ([:li [0 "rattata"]] [:li [1 "pidgey"]] [:li [2 "spearow"]])

我不是问一般的clojure‘for’,因为另一种迭代向量的方法也会让我满意。

这实际上是一个一般的clojure问题,而不是特定于试剂,但有几种方法可以做到这一点

您可以使用类似于当前代码的方法

(def items ["rattata" "pidgey" "spearow"])
(for [index (range (count items))]
  [:li (get items index) index])
你也可以使用


本例中的是试剂,因为
map
和friends返回可能干扰试剂的惰性列表(如果您忘记了,它将向控制台打印一条警告)。

您还可以将map索引与for循环相结合:

(for [[index item] (map-indexed vector items)]
  [:li item index])])

; vector function is a shorthand:
(for [[index item] (map-indexed (fn [index item] [index item]) items)]
  [:li item index])])

对于索引的宏,您可以使用

(defmacro for-indexed [[item index coll] & body]
  `(for [i# (range (count ~coll))] 
     (let [~item (nth ~coll i#)
           ~index i#]
       ~@body)))
  
(for-indexed [item index ["rattata" "pidgey" "spearow"]]
  [:li item index])

;; => ([:li "rattata" 0] [:li "pidgey" 1] [:li "spearow" 2])
或者,不要在绑定中传递
索引
,并将
用于索引
返回
[index item]
向量,如下所示:

(for [item ["rattata" "pidgey" "spearow"]]
  [:li item])])
  [:li item index]
(defmacro for-indexed [[item coll] & body]
  `(for [i# (range (count ~coll))] 
     (let [~item [i# (nth ~coll i#)]]
       ~@body)))

(for-indexed [item ["rattata" "pidgey" "spearow"]]
  [:li item])

;; => ([:li [0 "rattata"]] [:li [1 "pidgey"]] [:li [2 "spearow"]])

映射索引
映射
两个集合,其中一个集合是一个集合。那么,在这种情况下有没有理由使用“for”呢?map似乎更简洁:
(map子组件函数集合)
与:
(for[item collection](子组件函数项))
我问的是关于试剂的问题,因为页面上示例中的所有迭代都使用“for”。事实上,我会发现使用“地图”或“地图索引”更具可读性,而且它是有效的,所以我想知道为什么它们是“用于”的。对Clojure来说还是很新的,恐怕我在这里遗漏了一些东西。经过一些调查:映射索引是可以的,但不实例化react组件,也不允许在函数中取消对原子的引用。当与doall一起使用时,它允许您解除对atom的引用,但仍然不会创建组件。因为这是一条路要走,虽然它应该是[索引(范围(计数项))]另一个好的选择是
(映射索引(fn[索引项]^{:key index}[组件索引项])项)