4

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

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

我想获取特定项目的索引 - 像这样:

  [:li item index]

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

4

3 回答 3

7

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

您可以使用类似于当前代码的方法来处理它

(def items ["rattata" "pidgey" "spearow"])
(for [index (range (count items))]
  [:li (get items index) index])

您还可以使用地图索引

(doall (map-indexed (fn [index item] [:li index item]) items))

在这种情况下, doall用于 Reagent,因为map和朋友返回可能干扰 Reagent 的惰性列表(如果您忘记它,它将向控制台打印警告)。

于 2016-08-08T13:21:19.563 回答
4

您还可以将 map-indexed 与 for-loop 结合使用:

(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])])
于 2017-01-23T11:55:56.660 回答
1

你可以把自己当作一个for-indexed宏:

(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绑定并具有如下for-indexed返回[index item]向量:

(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"]])
于 2020-08-19T05:12:21.253 回答