向量到 ClojureScript 中的元素?

Vector to Elements in ClojureScript?

我有一个向量:

(def my-collection ["image1.jpg" "image2.jpg" "image3.jpg"])

我想在文档中制作 3 张图像。

(println (count my-collection)) ; this prints count of my collection. This is 3.

(map (fn [x] (println x)) my-collection) ; doesn't do anything!

但是!

(def image-element (.createElement js/document "img"))
(def insert-into-body (.appendChild (.-body js/document) image-element))
(set! (.-src image-element) "image1.jpg")

此代码对一个元素非常有效!

我应该为collection做什么?

map 函数用于通过应用指定函数将集合转换为另一个集合。由于 (println x) returns nil,您的代码的结果将是 (nil, nil, nil) 并具有副作用(每个图像名称都打印在您的控制台中)。

也许您想定义一个函数来创建具有指定 src 的图像元素。

(defn create-image [src]
  (let [img (.createElement js/document "img")]
    (set! (.-src img) src)
    img))

现在,您可以提供集合以将图像名称映射到图像元素,然后将它们附加到正文元素中。

(doseq [i (map create-image my-collection)]
  (.appendChild (.-body js/document) i))